Merge branch 'master' into oas3_support2

This commit is contained in:
wing328
2018-04-02 16:34:11 +08:00
37 changed files with 9246 additions and 5095 deletions

View File

@@ -185,9 +185,9 @@ void
QJsonObject obj = doc.object();
foreach(QString key, obj.keys()) {
qint32* val;
{{returnBaseType}} val;
setValue(&val, obj[key], "{{returnBaseType}}", QString());
output->insert(key, *val);
output->insert(key, val);
}
{{/isMapContainer}}
{{^isMapContainer}}

View File

@@ -2,6 +2,7 @@
use std::rc::Rc;
use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::HashMap;
use hyper;
use serde_json;
@@ -39,26 +40,71 @@ impl<C: hyper::client::Connect>{{classname}} for {{classname}}Client<C> {
fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box<Future<Item = {{^returnType}}(){{/returnType}}{{#returnType}}{{{.}}}{{/returnType}}, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
{{#hasAuthMethods}}
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
{{#authMethods}}
{{#isApiKey}}
if let Some(ref apikey) = configuration.api_key {
let key = apikey.key.clone();
let val = match apikey.prefix {
Some(ref prefix) => format!("{} {}", prefix, key),
None => key,
};
{{#isKeyInHeader}}
auth_headers.insert("{{keyParamName}}".to_owned(), val);
{{/isKeyInHeader}}
{{#isKeyInQuery}}
auth_query.insert("{{keyParamName}}".to_owned(), val);
{{/isKeyInQuery}}
};
{{/isApiKey}}
{{#isBasic}}
if let Some(ref auth_conf) = configuration.basic_auth {
let auth = hyper::header::Authorization(
hyper::header::Basic {
username: auth_conf.0.to_owned(),
password: auth_conf.1.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
let method = hyper::Method::{{httpMethod}};
{{^hasQueryParams}}
let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}});
{{/hasQueryParams}}
{{#hasQueryParams}}
let query = ::url::form_urlencoded::Serializer::new(String::new())
{{#queryParams}}
.append_pair("{{baseName}}", &{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
{{/queryParams}}
.finish();
let uri_str = format!("{}{{{path}}}{}", configuration.base_path, query{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}});
{{/hasQueryParams}}
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
{{#queryParams}}
query.append_pair("{{baseName}}", &{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/queryParams}}
{{#hasAuthMethods}}
for (key, val) in &auth_query {
query.append_pair(key, val);
}
{{/hasAuthMethods}}
query.finish()
};
let uri_str = format!("{}{{{path}}}?{}", configuration.base_path, query_string{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}});
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
@@ -73,6 +119,12 @@ impl<C: hyper::client::Connect>{{classname}} for {{classname}}Client<C> {
}
{{/hasHeaderParams}}
{{#hasAuthMethods}}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
{{/hasAuthMethods}}
{{#hasBodyParam}}
{{#bodyParams}}
let serialized = serde_json::to_string(&{{paramName}}).unwrap();

View File

@@ -1,10 +1,22 @@
{{>partial_header}}
use hyper;
use std::collections::HashMap;
pub struct Configuration<C: hyper::client::Connect> {
pub base_path: String,
pub user_agent: Option<String>,
pub client: hyper::client::Client<C>,
pub basic_auth: Option<BasicAuth>,
pub oauth_access_token: Option<String>,
pub api_key: Option<ApiKey>,
// TODO: take an oauth2 token source, similar to the go one
}
pub type BasicAuth = (String, Option<String>);
pub struct ApiKey {
pub prefix: Option<String>,
pub key: String,
}
impl<C: hyper::client::Connect> Configuration<C> {
@@ -13,6 +25,9 @@ impl<C: hyper::client::Connect> Configuration<C> {
base_path: "{{{basePath}}}".to_owned(),
user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("Swagger-Codegen/{{version}}/rust".to_owned()){{/httpUserAgent}},
client: client,
basic_auth: None,
oauth_access_token: None,
api_key: None,
}
}
}

View File

@@ -471,7 +471,7 @@ paths:
X-Expires-After:
type: string
format: date-time
description: date in UTC when toekn expires
description: date in UTC when token expires
'400':
description: Invalid username/password supplied
/user/logout:
@@ -919,6 +919,24 @@ paths:
responses:
'200':
description: successful operation
/fake/body-with-query-params:
put:
operationId: testBodyWithQueryParams
parameters:
- name: body
in: body
required: true
schema:
$ref: '#/definitions/User'
- name: query
in: query
required: true
type: string
consumes:
- application/json
responses:
'200':
description: Success
/another-fake/dummy:
patch:
tags:

View File

@@ -0,0 +1,50 @@
[package]
name = "{{packageName}}"
version = "{{appVersion}}"
authors = [{{#infoEmail}}"{{infoEmail}}"{{/infoEmail}}]
{{#appDescription}}
description = "{{{appDescription}}}"
{{/appDescription}}
license = "Unlicense"
[features]
default = ["client", "server"]
client = ["serde_json", {{#usesUrlEncodedForm}}"serde_urlencoded", {{/usesUrlEncodedForm}} {{#usesXml}}"serde-xml-rs", {{/usesXml}}"serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid"{{#apiHasFile}}, "multipart"{{/apiHasFile}}]
server = ["serde_json", {{#usesXml}}"serde-xml-rs", {{/usesXml}}"serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "tokio-proto", "tokio-tls", "regex", "percent-encoding", "url", "uuid"{{#apiHasFile}}, "multipart"{{/apiHasFile}}]
[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 = "0.9"
# 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
{{#usesXml}}serde-xml-rs = {git = "git://github.com/Metaswitch/serde-xml-rs.git" , branch = "master", optional = true}{{/usesXml}}
[dev-dependencies]
clap = "2.25"
error-chain = "0.11"

View File

@@ -0,0 +1,437 @@
#![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;
{{#apiHasFile}}extern crate multipart;{{/apiHasFile}}
{{#usesUrlEncodedForm}}extern crate serde_urlencoded;{{/usesUrlEncodedForm}}
{{#apiUsesUuid}}use uuid;{{/apiUsesUuid}}
{{#apiHasFile}}use self::multipart::client::lazy::Multipart;{{/apiHasFile}}
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;
{{#usesXml}}use serde_xml_rs;{{/usesXml}}
#[allow(unused_imports)]
use std::collections::{HashMap, BTreeMap};
#[allow(unused_imports)]
use swagger;
use swagger::{Context, ApiError, XSpanId};
use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}},
{{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
};
use models;
/// 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<String, ClientInitError> {
// 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.
#[derive(Clone)]
pub struct Client {
hyper_client: Arc<Fn(&Handle) -> Box<hyper::client::Service<Request=hyper::Request<hyper::Body>, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>,
handle: Arc<Handle>,
base_path: String,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Client {{ base_path: {} }}", self.base_path)
}
}
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<Client, ClientInitError> {
let http_connector = swagger::http_connector();
Self::try_new_with_connector::<hyper::client::HttpConnector>(
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<CA>(
handle: Handle,
base_path: &str,
ca_certificate: CA,
) -> Result<Client, ClientInitError>
where
CA: AsRef<Path>,
{
let https_connector = swagger::https_connector(ca_certificate);
Self::try_new_with_connector::<hyper_tls::HttpsConnector<hyper::client::HttpConnector>>(
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<CA, K, C, T>(
handle: Handle,
base_path: &str,
ca_certificate: CA,
client_key: K,
client_certificate: C,
) -> Result<Client, ClientInitError>
where
CA: AsRef<Path>,
K: AsRef<Path>,
C: AsRef<Path>,
{
let https_connector =
swagger::https_mutual_connector(ca_certificate, client_key, client_certificate);
Self::try_new_with_connector::<hyper_tls::HttpsConnector<hyper::client::HttpConnector>>(
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<C>(
handle: Handle,
base_path: &str,
protocol: Option<&'static str>,
connector_fn: Box<Fn(&Handle) -> C + Send + Sync>,
) -> Result<Client, ClientInitError>
where
C: hyper::client::Connect + hyper::client::Service,
{
let hyper_client = {
move |handle: &Handle| -> Box<
hyper::client::Service<
Request = hyper::Request<hyper::Body>,
Response = hyper::Response,
Error = hyper::Error,
Future = hyper::client::FutureResponse,
>,
> {
let connector = connector_fn(handle);
Box::new(hyper::Client::configure().connector(connector).build(
handle,
))
}
};
Ok(Client {
hyper_client: Arc::new(hyper_client),
handle: Arc::new(handle),
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.
pub fn try_new_with_hyper_client(hyper_client: Arc<Fn(&Handle) -> Box<hyper::client::Service<Request=hyper::Request<hyper::Body>, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>> + Sync + Send>,
handle: Handle,
base_path: &str)
-> Result<Client, ClientInitError>
{
Ok(Client {
hyper_client: hyper_client,
handle: Arc::new(handle),
base_path: into_base_path(base_path, None)?,
})
}
}
impl Api for Client {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, param_{{paramName}}: {{^required}}{{#isFile}}Box<Future<Item={{/isFile}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box<Future<Item={{operationId}}Response, Error=ApiError>> {
{{#queryParams}}{{#-first}}
// Query parameters
{{/-first}}{{#required}} let query_{{paramName}} = format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=param_{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}});
{{/required}}{{^required}} let query_{{paramName}} = param_{{paramName}}.map_or_else(String::new, |query| format!("{{baseName}}={{=<% %>=}}{<% paramName %>}<%={{ }}=%>&", {{paramName}}=query{{#isListContainer}}.join(","){{/isListContainer}}{{^isListContainer}}.to_string(){{/isListContainer}}));
{{/required}}{{/queryParams}}
let uri = format!(
"{}{{basePathWithoutHost}}{{path}}{{#queryParams}}{{#-first}}?{{/-first}}{{=<% %>=}}{<% paramName %>}<%={{ }}=%>{{/queryParams}}",
self.base_path{{#pathParams}}, {{baseName}}=utf8_percent_encode(&param_{{paramName}}.to_string(), PATH_SEGMENT_ENCODE_SET){{/pathParams}}{{#queryParams}},
{{paramName}}=utf8_percent_encode(&query_{{paramName}}, QUERY_ENCODE_SET){{/queryParams}}
);
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::{{#vendorExtensions}}{{HttpMethod}}{{/vendorExtensions}}, uri);
{{#vendorExtensions}}{{#hasFile}} // Form data body
let mut multipart = Multipart::new();
// Helper function to convert a Stream into a String. The String can then be used to build the HTTP body.
fn convert_stream_to_string(stream: Box<Stream<Item=Vec<u8>, Error=Error> + Send>) -> Result<String, ApiError> {
stream.concat2()
.wait()
.map_err(|e| ApiError(format!("Unable to collect stream: {}", e)))
.and_then(|body| String::from_utf8(body)
.map_err(|e| ApiError(format!("Failed to convert utf8 stream to String: {}", e))))
}{{/hasFile}}{{/vendorExtensions}}{{#formParams}}{{#isFile}}
{{^required}} if let Ok(Some(param_{{paramName}})) = param_{{paramName}}.wait() { {{/required}}
{{^required}} {{/required}} match convert_stream_to_string(param_{{paramName}}) {
{{^required}} {{/required}} Ok(param_{{paramName}}) => {
// Add file to multipart form.
multipart.add_text("{{paramName}}", param_{{paramName}});
},
{{^required}} {{/required}} Err(err) => return Box::new(futures::done(Err(err))),
{{^required}} {{/required}} }
{{^required}}}{{/required}}{{/isFile}}{{/formParams}}{{#vendorExtensions}}{{#hasFile}}
let mut fields = match multipart.prepare() {
Ok(fields) => fields,
Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build request: {}", err))))),
};
let mut body_string = String::new();
let body = fields.to_body().read_to_string(&mut body_string);
let boundary = fields.boundary();
let multipart_header = match mime::Mime::from_str(&format!("multipart/form-data;boundary={}", boundary)) {
Ok(multipart_header) => multipart_header,
Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build multipart header: {:?}", err))))),
};{{/hasFile}}{{^hasFile}}{{#formParams}}{{#-first}} let params = &[{{/-first}}
("{{baseName}}", {{#vendorExtensions}}{{#required}}Some({{#isString}}param_{{paramName}}{{/isString}}{{^isString}}format!("{:?}", param_{{paramName}}){{/isString}}){{/required}}{{^required}}{{#isString}}param_{{paramName}}{{/isString}}{{^isString}}param_{{paramName}}.map(|param| format!("{:?}", param)){{/isString}}{{/required}}),{{/vendorExtensions}}{{#-last}}
];
let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize");
request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}.clone()));
request.set_body(body.into_bytes());{{/-last}}{{/formParams}}{{/hasFile}}{{/vendorExtensions}}{{#bodyParam}}{{#-first}}
// Body parameter
{{/-first}}{{#vendorExtensions}}{{#required}}{{#consumesPlainText}} let body = param_{{paramName}};{{/consumesPlainText}}{{#consumesXml}}
{{^has_namespace}} let body = serde_xml_rs::to_string(&param_{{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(&param_{{paramName}}, namespaces).expect("impossible to fail to serialize");{{/has_namespace}}{{/consumesXml}}{{#consumesJson}}
let body = serde_json::to_string(&param_{{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}}
{{#bodyParam}}{{^required}}if let Some(body) = body {
{{/required}} request.set_body(body.into_bytes());
{{^required}} }{{/required}}
request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}.clone()));
{{/bodyParam}}
context.x_span_id.as_ref().map(|header| request.headers_mut().set(XSpanId(header.clone())));
{{#authMethods}}{{#isBasic}} context.auth_data.as_ref().map(|auth_data| {
if let &swagger::AuthData::Basic(ref basic_header) = auth_data {
request.headers_mut().set(hyper::header::Authorization(
basic_header.clone(),
))
}
});{{/isBasic}}{{/authMethods}}{{#headerParams}}{{#-first}}
// Header parameters
{{/-first}}{{^isMapContainer}} header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} }
{{#required}} request.headers_mut().set(Request{{vendorExtensions.typeName}}(param_{{paramName}}{{#isListContainer}}.clone(){{/isListContainer}}));
{{/required}}{{^required}} param_{{paramName}}.map(|header| request.headers_mut().set(Request{{vendorExtensions.typeName}}(header{{#isListContainer}}.clone(){{/isListContainer}})));
{{/required}}{{/isMapContainer}}{{#isMapContainer}} let param_{{paramName}}: Option<{{{dataType}}}> = None;
{{/isMapContainer}}{{/headerParams}}
{{#vendorExtensions}}{{#hasFile}}
request.headers_mut().set(ContentType(multipart_header));
request.set_body(body_string.into_bytes());
{{/hasFile}}{{/vendorExtensions}}
let hyper_client = (self.hyper_client)(&*self.handle);
Box::new(hyper_client.call(request)
.map_err(|e| ApiError(format!("No response received: {}", e)))
.and_then(|mut response| {
match response.status().as_u16() {
{{#responses}}
{{code}} => {
{{#headers}} header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] }
let response_{{name}} = match response.headers().get::<Response{{nameInCamelCase}}>() {
Some(response_{{name}}) => response_{{name}}.0.clone(),
None => return Box::new(future::err(ApiError(String::from("Required response header {{baseName}} for response {{code}} was not found.")))) as Box<Future<Item=_, Error=_>>,
};
{{/headers}}
{{^isFile}}let body = response.body();{{/isFile}}{{#isFile}}let body = Box::new(response.body()
.map(|chunk| chunk.to_vec())
.map_err(|_|
Error::new(ErrorKind::Other, "Received error reading response.")
));{{/isFile}}
Box::new(
{{#dataType}}{{^isFile}}
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|
{{#vendorExtensions}}{{#producesXml}}
// 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::<{{{dataType}}}>(body)
.map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))
{{/producesXml}}{{#producesJson}}
serde_json::from_str::<{{{dataType}}}>(body)
.map_err(|e| e.into())
{{/producesJson}}{{#producesPlainText}}
Ok(body.to_string())
{{/producesPlainText}}{{/vendorExtensions}}
))
.map(move |body|
{{/isFile}}{{#isFile}}
future::ok(
{{/isFile}}
{{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{^headers}}(body){{/headers}}{{#headers}}{{#-first}}{ body: body, {{/-first}}{{name}}: response_{{name}}{{^-last}}, {{/-last}}{{#-last}} }{{/-last}}{{/headers}}
)
{{/dataType}}{{^dataType}}
future::ok(
{{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}{{#headers}}{{#-first}}{ {{/-first}}{{^-first}}, {{/-first}}{{name}}: response_{{name}}{{#-last}} }{{/-last}}{{/headers}}
)
{{/dataType}}
) as Box<Future<Item=_, Error=_>>
},
{{/responses}}
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!("<Body was not UTF8: {:?}>", e)),
},
Err(e) => Cow::from(format!("<Failed to read body: {}>", e)),
})))
)
) as Box<Future<Item=_, Error=_>>
}
}
}))
}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}
#[derive(Debug)]
pub enum ClientInitError {
InvalidScheme,
InvalidUri(hyper::error::UriError),
MissingHost,
SslError(openssl::error::ErrorStack)
}
impl From<hyper::error::UriError> for ClientInitError {
fn from(err: hyper::error::UriError) -> ClientInitError {
ClientInitError::InvalidUri(err)
}
}
impl From<openssl::error::ErrorStack> 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."
}
}

View File

@@ -0,0 +1,79 @@
#![allow(missing_docs, unused_variables, trivial_casts)]
extern crate {{externCrateName}};
#[allow(unused_extern_crates)]
extern crate futures;
#[allow(unused_extern_crates)]
extern crate swagger;
#[allow(unused_extern_crates)]
extern crate uuid;
extern crate clap;
extern crate tokio_core;
#[allow(unused_imports)]
use futures::{Future, future, Stream, stream};
use tokio_core::reactor;
#[allow(unused_imports)]
use {{externCrateName}}::{ApiNoContext, ContextWrapperExt,
ApiError{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}},
{{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
};
use clap::{App, Arg};
fn main() {
let matches = App::new("client")
.arg(Arg::with_name("operation")
.help("Sets the operation to run")
.possible_values(&[
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#vendorExtensions}}{{^noClientExample}} "{{operationId}}",
{{/noClientExample}}{{/vendorExtensions}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}])
.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("{{serverHost}}")
.help("Hostname to contact"))
.arg(Arg::with_name("port")
.long("port")
.takes_value(true)
.default_value("{{serverPort}}")
.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
{{externCrateName}}::Client::try_new_https(core.handle(), &base_url, "examples/ca.pem")
.expect("Failed to create HTTPS client")
} else {
// Using HTTP
{{externCrateName}}::Client::try_new_http(core.handle(), &base_url)
.expect("Failed to create HTTP client")
};
// Using a non-default `Context` is not required; this is just an example!
let client = client.with_context({{externCrateName}}::Context::new_with_span_id(self::uuid::Uuid::new_v4().to_string()));
match matches.value_of("operation") {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#vendorExtensions}}{{#noClientExample}}// Disabled because there's no example.
// {{/noClientExample}}Some("{{operationId}}") => {
{{#noClientExample}}// {{/noClientExample}} let result = core.run(client.{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^-first}}, {{/-first}}{{#vendorExtensions}}{{{example}}}{{/vendorExtensions}}{{/allParams}}));
{{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
{{#vendorExtensions}}{{#noClientExample}}// {{/noClientExample}}{{/vendorExtensions}} },
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
_ => {
panic!("Invalid operation provided")
}
}
}

View File

@@ -0,0 +1,74 @@
//! Main binary entry point for {{externCrateName}} implementation.
#![allow(missing_docs)]
// Imports required by this file.
// extern crate <name of this crate>;
extern crate {{externCrateName}};
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 {{externCrateName}};
// extern crate swagger;
extern crate futures;
extern crate chrono;
#[macro_use]
extern crate error_chain;
{{#apiUsesUuid}}extern crate uuid;{{/apiUsesUuid}}
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;
mod server_lib;
// Builds an SSL implementation for Simple HTTPS from some hard-coded file names
fn ssl() -> Result<SslAcceptorBuilder, ErrorStack> {
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 =
{{externCrateName}}::server::auth::NewService::new(
AllowAllAuthenticator::new(
server_lib::NewService,
"cosmo"
)
);
let addr = "127.0.0.1:{{serverPort}}".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);
}
}

View File

@@ -0,0 +1,26 @@
//! Main library entry point for {{externCrateName}} implementation.
mod server;
mod errors {
error_chain!{}
}
pub use self::errors::*;
use std::io;
use hyper;
use {{externCrateName}};
pub struct NewService;
impl hyper::server::NewService for NewService {
type Request = (hyper::Request, {{externCrateName}}::Context);
type Response = hyper::Response;
type Error = hyper::Error;
type Instance = {{externCrateName}}::server::Service<server::Server>;
/// Instantiate a new server.
fn new_service(&self) -> io::Result<Self::Instance> {
Ok({{externCrateName}}::server::Service::new(server::Server))
}
}

View File

@@ -0,0 +1,31 @@
//! Server implementation of {{externCrateName}}.
#![allow(unused_imports)]
use futures::{self, Future};
use chrono;
{{#apiHasFile}}use futures::Stream;{{/apiHasFile}}
use std::collections::HashMap;
{{#apiHasFile}}use std::io::Error;{{/apiHasFile}}
{{#apiUsesUuid}}use uuid;{{/apiUsesUuid}}
use swagger;
use {{externCrateName}}::{Api, ApiError, Context{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}},
{{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
};
use {{externCrateName}}::models;
#[derive(Copy, Clone)]
pub struct Server;
impl Api for Server {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#summary}} /// {{{summary}}}{{/summary}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box<Future<Item={{/isFile}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box<Future<Item={{operationId}}Response, Error=ApiError>> {
let context = context.clone();
println!("{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{^isFile}}{{#vendorExtensions}}{{{formatString}}}{{/vendorExtensions}}{{#hasMore}}, {{/hasMore}}{{/isFile}}{{/allParams}}) - X-Span-ID: {:?}"{{#allParams}}{{^isFile}}, {{paramName}}{{/isFile}}{{/allParams}}, context.x_span_id.unwrap_or(String::from("<none>")).clone());{{#allParams}}{{#isFile}}
let _ = {{paramName}}; //Suppresses unused param warning{{/isFile}}{{/allParams}}
Box::new(futures::failed("Generic failure".into()))
}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}

View File

@@ -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;
{{#apiUsesUuid}}extern crate uuid;{{/apiUsesUuid}}
{{#usesXml}}extern crate serde_xml_rs;{{/usesXml}}
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;
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, Context, ContextWrapper};
pub const BASE_PATH: &'static str = "{{basePathWithoutHost}}";
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{^isResponseFile}}
#[derive(Debug, PartialEq)]
{{/isResponseFile}}
pub enum {{operationId}}Response {
{{#responses}}
{{#message}} /// {{message}}{{/message}}
{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}} {{#dataType}}{{^headers}}( {{{dataType}}} ) {{/headers}}{{#headers}}{{#-first}}{ body: {{{dataType}}}{{/-first}}{{/headers}}{{/dataType}}{{#headers}}{{#-first}}{{^dataType}} { {{/dataType}}{{#dataType}}, {{/dataType}}{{/-first}}{{^-first}}, {{/-first}}{{name}}: {{{datatype}}}{{#-last}} } {{/-last}}{{/headers}},
{{/responses}}
}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
/// API
pub trait Api {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#summary}} /// {{{summary}}}{{/summary}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box<Future<Item={{/isFile}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}, context: &Context) -> Box<Future<Item={{operationId}}Response, Error=ApiError>>;
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}
/// API without a `Context`
pub trait ApiNoContext {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#summary}} /// {{{summary}}}{{/summary}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box<Future<Item={{/isFile}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}) -> Box<Future<Item={{operationId}}Response, Error=ApiError>>;
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}
/// Trait to extend an API to make it easy to bind it to a context.
pub trait ContextWrapperExt<'a> where Self: Sized {
/// Binds this API to a context.
fn with_context(self: &'a Self, context: Context) -> ContextWrapper<'a, Self>;
}
impl<'a, T: Api + Sized> ContextWrapperExt<'a> for T {
fn with_context(self: &'a T, context: Context) -> ContextWrapper<'a, T> {
ContextWrapper::<T>::new(self, context)
}
}
impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
{{#summary}} /// {{{summary}}}{{/summary}}
fn {{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}(&self{{#allParams}}, {{paramName}}: {{^required}}{{#isFile}}Box<Future<Item={{/isFile}}Option<{{/required}}{{#isListContainer}}&{{/isListContainer}}{{{dataType}}}{{^required}}>{{#isFile}}, Error=Error> + Send>{{/isFile}}{{/required}}{{/allParams}}) -> Box<Future<Item={{operationId}}Response, Error=ApiError>> {
self.api().{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}{{paramName}}, {{/allParams}}&self.context())
}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}
#[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;

View File

@@ -0,0 +1,25 @@
/// mime types for requests and responses
pub mod responses {
use hyper::mime::*;
// The macro is called per-operation to beat the recursion limit
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#responses}}{{#produces}}{{#-first}}{{#dataType}} /// Create Mime objects for the response content types for {{operationId}}
lazy_static! {
pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}: Mime = "{{{mediaType}}}".parse().unwrap();
}
{{/dataType}}{{/-first}}{{/produces}}{{/responses}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}
pub mod requests {
use hyper::mime::*;
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#bodyParam}} /// Create Mime objects for the request content types for {{operationId}}
lazy_static! {
pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}: Mime = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}application/json{{/consumes}}".parse().unwrap();
}
{{/bodyParam}}{{^bodyParam}}{{#vendorExtensions}}{{#formParams}}{{#-first}}{{^hasFile}} /// Create Mime objects for the request content types for {{operationId}}
lazy_static! {
pub static ref {{#vendorExtensions}}{{uppercase_operation_id}}{{/vendorExtensions}}: Mime = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}application/x-www-form-urlencoded{{/consumes}}".parse().unwrap();
}
{{/hasFile}}{{/-first}}{{/formParams}}{{/vendorExtensions}}{{/bodyParam}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}

View File

@@ -0,0 +1,95 @@
use std::io;
use hyper;
use hyper::{Request, Response, Error, StatusCode};
use server::url::form_urlencoded;
use swagger::auth::{Authorization, AuthData, Scopes};
use Api;
pub struct NewService<T> where T: hyper::server::NewService<Request=(Request,Option<AuthData>), Response=Response, Error=Error> {
inner: T,
}
impl<T> NewService<T> where T: hyper::server::NewService<Request=(Request,Option<AuthData>), Response=Response, Error=Error> + 'static {
pub fn new(inner: T) -> NewService<T> {
NewService{inner}
}
}
impl<T> hyper::server::NewService for NewService<T> where T: hyper::server::NewService<Request=(Request,Option<AuthData>), Response=Response, Error=Error> + 'static {
type Request = Request;
type Response = Response;
type Error = Error;
type Instance = Service<T::Instance>;
fn new_service(&self) -> Result<Self::Instance, io::Error> {
self.inner.new_service().map(|s| Service::new(s))
}
}
/// Middleware to extract authentication data from request
pub struct Service<T> where T: hyper::server::Service<Request=(Request,Option<AuthData>), Response=Response, Error=Error> {
inner: T,
}
impl<T> Service<T> where T: hyper::server::Service<Request=(Request,Option<AuthData>), Response=Response, Error=Error> {
pub fn new(inner: T) -> Service<T> {
Service{inner}
}
}
impl<T> hyper::server::Service for Service<T> where T: hyper::server::Service<Request=(Request,Option<AuthData>), Response=Response, Error=Error> {
type Request = Request;
type Response = Response;
type Error = Error;
type Future = T::Future;
fn call(&self, req: Self::Request) -> Self::Future {
{{#authMethods}}
{{#isBasic}}
{
use hyper::header::{Authorization, Basic, Bearer};
use std::ops::Deref;
if let Some(basic) = req.headers().get::<Authorization<Basic>>().cloned() {
let auth_data = AuthData::Basic(basic.deref().clone());
return self.inner.call((req, Some(auth_data)));
}
}
{{/isBasic}}
{{#isOAuth}}
{
use hyper::header::{Authorization, Basic, Bearer};
use std::ops::Deref;
if let Some(bearer) = req.headers().get::<Authorization<Bearer>>().cloned() {
let auth_data = AuthData::Bearer(bearer.deref().clone());
return self.inner.call((req, Some(auth_data)));
}
}
{{/isOAuth}}
{{#isApiKey}}
{{#isKeyInHeader}}
{
header! { (ApiKey{{-index}}, "{{keyParamName}}") => [String] }
if let Some(header) = req.headers().get::<ApiKey{{-index}}>().cloned() {
let auth_data = AuthData::ApiKey(header.0);
return self.inner.call((req, Some(auth_data)));
}
}
{{/isKeyInHeader}}
{{#isKeyInQuery}}
{
let key = form_urlencoded::parse(req.query().unwrap_or_default().as_bytes())
.filter(|e| e.0 == "api_key_query")
.map(|e| e.1.clone().into_owned())
.nth(0);
if let Some(key) = key {
let auth_data = AuthData::ApiKey(key);
return self.inner.call((req, Some(auth_data)));
}
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
return self.inner.call((req, None));
}
}

View File

@@ -0,0 +1,449 @@
#![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;
{{^apiUsesUuid}}extern crate uuid;{{/apiUsesUuid}}
extern crate chrono;
{{#apiHasFile}}extern crate multipart;{{/apiHasFile}}
extern crate percent_encoding;
extern crate url;
{{#apiUsesUuid}}use uuid;{{/apiUsesUuid}}
use std::sync::Arc;
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;
{{#apiHasFile}}use self::multipart::server::Multipart;
use self::multipart::server::save::SaveResult;{{/apiHasFile}}
use serde_json;
{{#usesXml}}use serde_xml_rs;{{/usesXml}}
#[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, Context, XSpanId};
use swagger::auth::Scopes;
use {Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}},
{{operationId}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
};
#[allow(unused_imports)]
use models;
pub mod auth;
header! { (Warning, "Warning") => [String] }
mod paths {
extern crate regex;
lazy_static! {
pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(&[
{{#pathSet}}
r"^{{basePathWithoutHost}}{{{pathRegEx}}}"{{^-last}},{{/-last}}
{{/pathSet}}
]).unwrap();
}
{{#pathSet}}
pub static ID_{{PATH_ID}}: usize = {{index}};
{{#hasPathParams}}
lazy_static! {
pub static ref REGEX_{{PATH_ID}}: regex::Regex = regex::Regex::new(r"^{{basePathWithoutHost}}{{{pathRegEx}}}").unwrap();
}
{{/hasPathParams}}
{{/pathSet}}
}
pub struct NewService<T> {
api_impl: Arc<T>,
}
impl<T> NewService<T> where T: Api + Clone + 'static {
pub fn new<U: Into<Arc<T>>>(api_impl: U) -> NewService<T> {
NewService{api_impl: api_impl.into()}
}
}
impl<T> hyper::server::NewService for NewService<T> where T: Api + Clone + 'static {
type Request = (Request, Context);
type Response = Response;
type Error = Error;
type Instance = Service<T>;
fn new_service(&self) -> Result<Self::Instance, io::Error> {
Ok(Service::new(self.api_impl.clone()))
}
}
pub struct Service<T> {
api_impl: Arc<T>,
}
impl<T> Service<T> where T: Api + Clone + 'static {
pub fn new<U: Into<Arc<T>>>(api_impl: U) -> Service<T> {
Service{api_impl: api_impl.into()}
}
}
impl<T> hyper::server::Service for Service<T> where T: Api + Clone + 'static {
type Request = (Request, Context);
type Response = Response;
type Error = Error;
type Future = Box<Future<Item=Response, Error=Error>>;
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());
match &method {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
// {{operationId}} - {{httpMethod}} {{path}}
&hyper::Method::{{vendorExtensions.HttpMethod}} if path.matched(paths::ID_{{vendorExtensions.PATH_ID}}) => {
if context.x_span_id.is_none() {
context.x_span_id = Some(headers.get::<XSpanId>().map(XSpanId::to_string).unwrap_or_else(|| self::uuid::Uuid::new_v4().to_string()));
}
{{#hasAuthMethods}}
{
let authorization = match context.authorization.as_ref() {
Some(authorization) => authorization,
None => return Box::new(future::ok(Response::new()
.with_status(StatusCode::Forbidden)
.with_body("Unauthenticated"))),
};
{{#authMethods}}
{{#isOAuth}}
// Authorization
if let Scopes::Some(ref scopes) = authorization.scopes {
let required_scopes: BTreeSet<String> = vec![
{{#scopes}}
"{{scope}}".to_string(), // {{description}}
{{/scopes}}
].into_iter().collect();
if !required_scopes.is_subset(scopes) {
let missing_scopes = required_scopes.difference(scopes);
return Box::new(future::ok(Response::new()
.with_status(StatusCode::Forbidden)
.with_body(missing_scopes.fold(
"Insufficient authorization, missing scopes".to_string(),
|s, scope| format!("{} {}", s, scope)
))
));
}
}
{{/isOAuth}}
{{/authMethods}}
}
{{/hasAuthMethods}}
{{#vendorExtensions}}{{#hasPathParams}}
// Path parameters
let path = uri.path().to_string();
let path_params =
paths::REGEX_{{PATH_ID}}
.captures(&path)
.unwrap_or_else(||
panic!("Path {} matched RE {{PATH_ID}} in set but failed match against \"{}\"", path, paths::REGEX_{{PATH_ID}}.as_str())
);
{{/hasPathParams}}{{/vendorExtensions}}
{{#pathParams}}
let param_{{paramName}} = match percent_encoding::percent_decode(path_params["{{baseName}}"].as_bytes()).decode_utf8() {
Ok(param_{{paramName}}) => match param_{{paramName}}.parse::<{{{dataType}}}>() {
Ok(param_{{paramName}}) => param_{{paramName}},
Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse path parameter {{baseName}}: {}", e)))),
},
Err(_) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't percent-decode path parameter as UTF-8: {}", &path_params["{{baseName}}"]))))
};
{{/pathParams}}
{{#headerParams}}{{#-first}}
// Header parameters
{{/-first}}
header! { (Request{{vendorExtensions.typeName}}, "{{baseName}}") => {{#isListContainer}}({{{baseType}}})*{{/isListContainer}}{{^isListContainer}}[{{{dataType}}}]{{/isListContainer}} }
{{#required}}
let param_{{paramName}} = match headers.get::<Request{{vendorExtensions.typeName}}>() {
Some(param_{{paramName}}) => param_{{paramName}}.0.clone(),
None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing or invalid required header {{baseName}}"))),
};
{{/required}}
{{^required}}
let param_{{paramName}} = headers.get::<Request{{vendorExtensions.typeName}}>().map(|header| header.0.clone());
{{/required}}{{/headerParams}}
{{#queryParams}}{{#-first}}
// Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response)
let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::<Vec<_>>();
{{/-first}}
let param_{{paramName}} = query_params.iter().filter(|e| e.0 == "{{baseName}}").map(|e| e.1.to_owned())
{{#isListContainer}}
.filter_map(|param_{{paramName}}| param_{{paramName}}.parse::<{{{baseType}}}>().ok())
.collect::<Vec<_>>();
{{^required}}
let param_{{paramName}} = if !param_{{paramName}}.is_empty() {
Some(param_{{paramName}})
} else {
None
};
{{/required}}
{{/isListContainer}}{{^isListContainer}}
.nth(0);
{{#required}}
let param_{{paramName}} = match param_{{paramName}} {
Some(param_{{paramName}}) => match param_{{paramName}}.parse::<{{{dataType}}}>() {
Ok(param_{{paramName}}) => param_{{paramName}},
Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse query parameter {{baseName}} - doesn't match schema: {}", e)))),
},
None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required query parameter {{baseName}}"))),
};
{{/required}}{{^required}}
let param_{{paramName}} = param_{{paramName}}.and_then(|param_{{paramName}}| param_{{paramName}}.parse::<{{{baseType}}}>().ok());
{{/required}}
{{/isListContainer}}
{{/queryParams}}
{{#bodyParams}}{{#-first}}
// 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<Future<Item=Response, Error=Error>> {
match result {
Ok(body) => {
{{#vendorExtensions}}{{^consumesPlainText}}
let mut unused_elements = Vec::new();
{{/consumesPlainText}}
let param_{{paramName}}: Option<{{{dataType}}}> = if !body.is_empty() {
{{#consumesXml}}
let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body);
{{/consumesXml}}{{#consumesJson}}
let deserializer = &mut serde_json::Deserializer::from_slice(&*body);
{{/consumesJson}}{{^consumesPlainText}}
match serde_ignored::deserialize(deserializer, |path| {
warn!("Ignoring unknown field in body: {}", path);
unused_elements.push(path.to_string());
}) {
Ok(param_{{paramName}}) => param_{{paramName}},
{{#required}}
Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter {{baseName}} - doesn't match schema: {}", e)))),
{{/required}}{{^required}}
Err(_) => None,
{{/required}}
}
{{/consumesPlainText}}{{#consumesPlainText}}
match String::from_utf8(body.to_vec()) {
Ok(param_{{paramName}}) => Some(param_{{paramName}}),
Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter {{baseName}} - not valid UTF-8: {}", e)))),
}
{{/consumesPlainText}}{{/vendorExtensions}}
} else {
None
};
{{#required}}
let param_{{paramName}} = match param_{{paramName}} {
Some(param_{{paramName}}) => param_{{paramName}},
None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter {{baseName}}"))),
};
{{/required}}
{{/-first}}{{/bodyParams}}
{{^bodyParams}}{{#vendorExtensions}}{{#hasFile}}
let boundary = match multipart_boundary(&headers) {
Some(boundary) => boundary.to_string(),
None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Couldn't find valid multipart body"))),
};
Box::new(body.concat2()
.then(move |result| -> Box<Future<Item=Response, Error=Error>> {
match result {
Ok(body) => {
let mut entries = match Multipart::with_body(&body.to_vec()[..], boundary).save().temp() {
SaveResult::Full(entries) => {
entries
},
_ => {
return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Unable to process all message parts"))))
},
};
{{#formParams}}{{#-first}}
// Form parameters
{{/-first}}
let param_{{paramName}} = entries.fields.remove("{{paramName}}");
let param_{{paramName}} = match param_{{paramName}} {
Some(entry) =>
{{#isFile}}
{{^required}}Some({{/required}}Box::new(stream::once(Ok(entry.as_bytes().to_vec()))) as Box<Stream<Item=Vec<u8>, Error=io::Error> + Send>{{^required}}){{/required}},
{{/isFile}}{{^isFile}}
match entry.parse::<{{{dataType}}}>() {
Ok(entry) => {{^required}}Some({{/required}}entry{{^required}}){{/required}},
{{#required}}
Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse form parameter {{baseName}} - doesn't match schema: {}", e)))),
{{/required}}{{^required}}
Err(_) => None,
{{/required}}
},
{{/isFile}}
{{#required}}
None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Missing required form parameter {{paramName}}")))),
{{/required}}{{^required}}
None => None,
{{/required}}
};
{{^required}}{{#isFile}} let param_{{paramName}} = Box::new(future::ok(param_{{paramName}}));{{/isFile}}{{/required}}
{{/formParams}}
{{/hasFile}}{{^hasFile}}
Box::new(({
{{
{{#formParams}}{{#-first}}
// Form parameters
{{/-first}}
let param_{{paramName}} = {{^isContainer}}{{#vendorExtensions}}{{{example}}};{{/vendorExtensions}}{{/isContainer}}{{#isListContainer}}{{#required}}Vec::new();{{/required}}{{^required}}None;{{/required}}{{/isListContainer}}{{#isMapContainer}}None;{{/isMapContainer}}
{{/formParams}}
{{/hasFile}}{{/vendorExtensions}}{{/bodyParams}}
Box::new(api_impl.{{#vendorExtensions}}{{operation_id}}{{/vendorExtensions}}({{#allParams}}param_{{paramName}}{{#isListContainer}}.as_ref(){{/isListContainer}}, {{/allParams}}&context)
.then(move |result| {
let mut response = Response::new();
context.x_span_id.as_ref().map(|header| response.headers_mut().set(XSpanId(header.clone())));
{{#bodyParams}}{{#vendorExtensions}}{{^consumesPlainText}}
if !unused_elements.is_empty() {
response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements)));
}
{{/consumesPlainText}}{{/vendorExtensions}}{{/bodyParams}}
match result {
Ok(rsp) => match rsp {
{{#responses}}
{{operationId}}Response::{{#vendorExtensions}}{{x-responseId}}{{/vendorExtensions}}
{{#dataType}}{{^headers}}
(body)
{{/headers}}{{#headers}}
{{#-first}}
{
body,
{{/-first}}
{{name}}{{^-last}}, {{/-last}}
{{#-last}}
}
{{/-last}}
{{/headers}}{{/dataType}}
{{^dataType}}{{#headers}}{{#-first}}
{
{{/-first}}
{{name}}{{^-last}}, {{/-last}}
{{#-last}}
}
{{/-last}}
{{/headers}}{{/dataType}}
=> {
{{^isFile}} response.set_status(StatusCode::try_from({{code}}).unwrap());
{{#headers}}
header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] }
response.headers_mut().set(Response{{nameInCamelCase}}({{name}}));
{{/headers}}
{{#produces}}{{#-first}}{{#dataType}}
response.headers_mut().set(ContentType(mimetypes::responses::{{#vendorExtensions}}{{uppercase_operation_id}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}.clone()));
{{/dataType}}{{/-first}}{{/produces}}
{{#dataType}}
{{#vendorExtensions}}{{#producesXml}}{{^has_namespace}}
let body = 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());
let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize");
{{/has_namespace}}{{/producesXml}}{{#producesJson}}
let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
{{/producesJson}}{{/vendorExtensions}}
response.set_body(body);
{{/dataType}}{{/isFile}}{{#isFile}}
let body = body.fold(Vec::new(), | mut body, chunk| {
body.extend(chunk.iter());
future::ok::<Vec<u8>, io::Error>(body)
})
// Block whilst waiting for the stream to complete
.wait();
match body {
// If no error occurred then create successful hyper response
Ok(vec) => {
response.set_status(StatusCode::try_from({{code}}).unwrap());
{{#headers}}
header! { (Response{{nameInCamelCase}}, "{{baseName}}") => [{{{datatype}}}] }
response.headers_mut().set(Response{{nameInCamelCase}}({{name}}));
{{/headers}}{{#produces}}{{#-first}}{{#dataType}}
response.headers_mut().set(ContentType(mimetypes::responses::{{#vendorExtensions}}{{uppercase_operation_id}}_{{x-uppercaseResponseId}}{{/vendorExtensions}}.clone()));
{{/dataType}}{{/-first}}{{/produces}}
response.set_body(vec);
},
// It's possible that errors were received in the stream, if this is the case then we can't return a success response to the client and instead must return an internal error.
Err(e) => {
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
}
}
{{/isFile}}
},
{{/responses}}
},
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)
}
))
{{^bodyParams}}{{#vendorExtensions}}{{^hasFile}}
}}
})) as Box<Future<Item=Response, Error=Error>>
{{/hasFile}}{{#hasFile}}
as Box<Future<Item=Response, Error=Error>>
},
Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read multipart body")))),
}
})
)
{{/hasFile}}{{/vendorExtensions}}{{/bodyParams}}
{{#bodyParams}}{{#-first}}
},
Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter {{baseName}}: {}", e)))),
}
})
) as Box<Future<Item=Response, Error=Error>>
{{/-first}}{{/bodyParams}}
},
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
_ => Box::new(future::ok(Response::new().with_status(StatusCode::NotFound))) as Box<Future<Item=Response, Error=Error>>,
}
}
}
{{#apiHasFile}}
/// Utility function to get the multipart boundary marker (if any) from the Headers.
fn multipart_boundary<'a>(headers: &'a Headers) -> Option<&'a str> {
headers.get::<ContentType>().and_then(|content_type| {
let ContentType(ref mime) = *content_type;
if mime.type_() == mime::MULTIPART && mime.subtype() == mime::FORM_DATA {
mime.get_param(mime::BOUNDARY).map(|x| x.as_str())
} else {
None
}
})
}
{{/apiHasFile}}

View File

@@ -126,9 +126,9 @@ SWGStoreApi::getInventoryCallback(SWGHttpRequestWorker * worker) {
QJsonObject obj = doc.object();
foreach(QString key, obj.keys()) {
qint32* val;
qint32 val;
setValue(&val, obj[key], "qint32", QString());
output->insert(key, *val);
output->insert(key, val);
}
worker->deleteLater();

View File

@@ -132,7 +132,7 @@ Get user by user name
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| The name that needs to be fetched. Use user1 for testing. |
**username** | **String**| The name that needs to be fetched. Use user1 for testing. |
### Return type

View File

@@ -9,11 +9,23 @@
*/
use hyper;
use std::collections::HashMap;
pub struct Configuration<C: hyper::client::Connect> {
pub base_path: String,
pub user_agent: Option<String>,
pub client: hyper::client::Client<C>,
pub basic_auth: Option<BasicAuth>,
pub oauth_access_token: Option<String>,
pub api_key: Option<ApiKey>,
// TODO: take an oauth2 token source, similar to the go one
}
pub type BasicAuth = (String, Option<String>);
pub struct ApiKey {
pub prefix: Option<String>,
pub key: String,
}
impl<C: hyper::client::Connect> Configuration<C> {
@@ -22,6 +34,9 @@ impl<C: hyper::client::Connect> Configuration<C> {
base_path: "http://petstore.swagger.io/v2".to_owned(),
user_agent: Some("Swagger-Codegen/1.0.0/rust".to_owned()),
client: client,
basic_auth: None,
oauth_access_token: None,
api_key: None,
}
}
}

View File

@@ -11,6 +11,7 @@
use std::rc::Rc;
use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::HashMap;
use hyper;
use serde_json;
@@ -49,22 +50,44 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
fn add_pet(&self, body: ::models::Pet) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Post;
let uri_str = format!("{}/pet", configuration.base_path);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
let serialized = serde_json::to_string(&body).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
@@ -94,16 +117,34 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
fn delete_pet(&self, pet_id: i64, api_key: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Delete;
let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
@@ -114,6 +155,10 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
headers.set_raw("api_key", api_key);
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
@@ -139,25 +184,45 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
fn find_pets_by_status(&self, status: Vec<String>) -> Box<Future<Item = Vec<::models::Pet>, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Get;
let query = ::url::form_urlencoded::Serializer::new(String::new())
.append_pair("status", &status.join(",").to_string())
.finish();
let uri_str = format!("{}/pet/findByStatus{}", configuration.base_path, query);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.append_pair("status", &status.join(",").to_string());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/findByStatus?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
@@ -186,25 +251,45 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
fn find_pets_by_tags(&self, tags: Vec<String>) -> Box<Future<Item = Vec<::models::Pet>, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Get;
let query = ::url::form_urlencoded::Serializer::new(String::new())
.append_pair("tags", &tags.join(",").to_string())
.finish();
let uri_str = format!("{}/pet/findByTags{}", configuration.base_path, query);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.append_pair("tags", &tags.join(",").to_string());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/findByTags?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
@@ -233,22 +318,44 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
fn get_pet_by_id(&self, pet_id: i64) -> Box<Future<Item = ::models::Pet, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
if let Some(ref apikey) = configuration.api_key {
let key = apikey.key.clone();
let val = match apikey.prefix {
Some(ref prefix) => format!("{} {}", prefix, key),
None => key,
};
auth_headers.insert("api_key".to_owned(), val);
};
let method = hyper::Method::Get;
let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
@@ -277,22 +384,44 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
fn update_pet(&self, body: ::models::Pet) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Put;
let uri_str = format!("{}/pet", configuration.base_path);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
let serialized = serde_json::to_string(&body).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
@@ -322,22 +451,44 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
fn update_pet_with_form(&self, pet_id: i64, name: &str, status: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Post;
let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
@@ -363,22 +514,44 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
fn upload_file(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box<Future<Item = ::models::ApiResponse, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Post;
let uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/{petId}/uploadImage?{}", configuration.base_path, query_string, petId=pet_id);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(

View File

@@ -11,6 +11,7 @@
use std::rc::Rc;
use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::HashMap;
use hyper;
use serde_json;
@@ -47,14 +48,19 @@ impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> {
let method = hyper::Method::Delete;
let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
@@ -62,6 +68,7 @@ impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> {
// send request
Box::new(
configuration.client.request(req)
@@ -86,22 +93,44 @@ impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> {
fn get_inventory(&self, ) -> Box<Future<Item = ::std::collections::HashMap<String, i32>, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
if let Some(ref apikey) = configuration.api_key {
let key = apikey.key.clone();
let val = match apikey.prefix {
Some(ref prefix) => format!("{} {}", prefix, key),
None => key,
};
auth_headers.insert("api_key".to_owned(), val);
};
let method = hyper::Method::Get;
let uri_str = format!("{}/store/inventory", configuration.base_path);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/store/inventory?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
@@ -132,14 +161,19 @@ impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> {
let method = hyper::Method::Get;
let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
@@ -147,6 +181,7 @@ impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> {
// send request
Box::new(
configuration.client.request(req)
@@ -176,20 +211,26 @@ impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> {
let method = hyper::Method::Post;
let uri_str = format!("{}/store/order", configuration.base_path);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/store/order?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&body).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));

View File

@@ -11,6 +11,7 @@
use std::rc::Rc;
use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::HashMap;
use hyper;
use serde_json;
@@ -51,20 +52,26 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
let method = hyper::Method::Post;
let uri_str = format!("{}/user", configuration.base_path);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&body).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
@@ -96,20 +103,26 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
let method = hyper::Method::Post;
let uri_str = format!("{}/user/createWithArray", configuration.base_path);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/createWithArray?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&body).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
@@ -141,20 +154,26 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
let method = hyper::Method::Post;
let uri_str = format!("{}/user/createWithList", configuration.base_path);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/createWithList?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&body).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
@@ -186,14 +205,19 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
let method = hyper::Method::Delete;
let uri_str = format!("{}/user/{username}", configuration.base_path, username=username);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
@@ -201,6 +225,7 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
// send request
Box::new(
configuration.client.request(req)
@@ -227,14 +252,19 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
let method = hyper::Method::Get;
let uri_str = format!("{}/user/{username}", configuration.base_path, username=username);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
@@ -242,6 +272,7 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
// send request
Box::new(
configuration.client.request(req)
@@ -271,18 +302,21 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
let method = hyper::Method::Get;
let query = ::url::form_urlencoded::Serializer::new(String::new())
.append_pair("username", &username.to_string())
.append_pair("password", &password.to_string())
.finish();
let uri_str = format!("{}/user/login{}", configuration.base_path, query);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.append_pair("username", &username.to_string());
query.append_pair("password", &password.to_string());
query.finish()
};
let uri_str = format!("{}/user/login?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
@@ -290,6 +324,7 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
// send request
Box::new(
configuration.client.request(req)
@@ -319,14 +354,19 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
let method = hyper::Method::Get;
let uri_str = format!("{}/user/logout", configuration.base_path);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/logout?{}", configuration.base_path, query_string);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
@@ -334,6 +374,7 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
// send request
Box::new(
configuration.client.request(req)
@@ -360,20 +401,26 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
let method = hyper::Method::Put;
let uri_str = format!("{}/user/{username}", configuration.base_path, username=username);
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username);
let uri = uri_str.parse();
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut req = hyper::Request::new(method, uri.unwrap());
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&body).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));

View File

@@ -1,294 +0,0 @@
//! Server implementation of petstore_api.
#![allow(unused_imports)]
use futures::{self, Future};
use chrono;
use futures::Stream;
use std::collections::HashMap;
use std::io::Error;
use swagger;
use petstore_api::{Api, ApiError, Context,
TestSpecialTagsResponse,
GetXmlFeaturesResponse,
PostPlainTextResponse,
PostXmlFeaturesResponse,
PutPlainTextResponse,
FakeOuterBooleanSerializeResponse,
FakeOuterCompositeSerializeResponse,
FakeOuterNumberSerializeResponse,
FakeOuterStringSerializeResponse,
TestClientModelResponse,
TestEndpointParametersResponse,
TestEnumParametersResponse,
TestJsonFormDataResponse,
TestClassnameResponse,
AddPetResponse,
DeletePetResponse,
FindPetsByStatusResponse,
FindPetsByTagsResponse,
GetPetByIdResponse,
UpdatePetResponse,
UpdatePetWithFormResponse,
UploadFileResponse,
DeleteOrderResponse,
GetInventoryResponse,
GetOrderByIdResponse,
PlaceOrderResponse,
CreateUserResponse,
CreateUsersWithArrayInputResponse,
CreateUsersWithListInputResponse,
DeleteUserResponse,
GetUserByNameResponse,
LoginUserResponse,
LogoutUserResponse,
UpdateUserResponse
};
use petstore_api::models;
#[derive(Copy, Clone)]
pub struct Server;
impl Api for Server {
/// To test special tags
fn test_special_tags(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("test_special_tags({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Get some XML
fn get_xml_features(&self, context: &Context) -> Box<Future<Item=GetXmlFeaturesResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("get_xml_features() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Post some plaintext
fn post_plain_text(&self, message: String, context: &Context) -> Box<Future<Item=PostPlainTextResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("post_plain_text(\"{}\") - X-Span-ID: {:?}", message, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Post some xml
fn post_xml_features(&self, xml_object: models::XmlObject, context: &Context) -> Box<Future<Item=PostXmlFeaturesResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("post_xml_features({:?}) - X-Span-ID: {:?}", xml_object, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Put some optional plaintext
fn put_plain_text(&self, message: Option<String>, context: &Context) -> Box<Future<Item=PutPlainTextResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("put_plain_text({:?}) - X-Span-ID: {:?}", message, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>, context: &Context) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>, context: &Context) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>, context: &Context) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>, context: &Context) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// To test \"client\" model
fn test_client_model(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClientModelResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("test_client_model({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>, context: &Context) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("test_endpoint_parameters({}, {}, \"{}\", \"{:?}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// To test enum parameters
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>, context: &Context) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// test json serialization of form data
fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// To test class name in snake case
fn test_classname(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClassnameResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("test_classname({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Add a new pet to the store
fn add_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=AddPetResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("add_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Deletes a pet
fn delete_pet(&self, pet_id: i64, api_key: Option<String>, context: &Context) -> Box<Future<Item=DeletePetResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Finds Pets by status
fn find_pets_by_status(&self, status: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Finds Pets by tags
fn find_pets_by_tags(&self, tags: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Find pet by ID
fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Update an existing pet
fn update_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=UpdatePetResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("update_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Updates a pet in the store with form data
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>, context: &Context) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// uploads an image
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box<Future<Item=UploadFileResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("upload_file({}, {:?}, ) - X-Span-ID: {:?}", pet_id, additional_metadata, context.x_span_id.unwrap_or(String::from("<none>")).clone());
let _ = file; //Suppresses unused param warning
Box::new(futures::failed("Generic failure".into()))
}
/// Delete purchase order by ID
fn delete_order(&self, order_id: String, context: &Context) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Returns pet inventories by status
fn get_inventory(&self, context: &Context) -> Box<Future<Item=GetInventoryResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("get_inventory() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Find purchase order by ID
fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Place an order for a pet
fn place_order(&self, body: models::Order, context: &Context) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("place_order({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Create user
fn create_user(&self, body: models::User, context: &Context) -> Box<Future<Item=CreateUserResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("create_user({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Creates list of users with given input array
fn create_users_with_array_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Creates list of users with given input array
fn create_users_with_list_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Delete user
fn delete_user(&self, username: String, context: &Context) -> Box<Future<Item=DeleteUserResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Get user by user name
fn get_user_by_name(&self, username: String, context: &Context) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Logs user into the system
fn login_user(&self, username: String, password: String, context: &Context) -> Box<Future<Item=LoginUserResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Logs out current logged in user session
fn logout_user(&self, context: &Context) -> Box<Future<Item=LogoutUserResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("logout_user() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Updated user
fn update_user(&self, username: String, body: models::User, context: &Context) -> Box<Future<Item=UpdateUserResponse, Error=ApiError> + Send> {
let context = context.clone();
println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
}

View File

@@ -1 +1 @@
2.3.0
2.4.0-SNAPSHOT

View File

@@ -7,32 +7,37 @@ license = "Unlicense"
[features]
default = ["client", "server"]
client = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "hyper-openssl", "uuid", "multipart"]
server = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "iron", "router", "bodyparser", "urlencoded", "uuid", "multipart"]
client = ["serde_json", "serde_urlencoded", "serde-xml-rs", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid", "multipart"]
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", "multipart"]
[dependencies]
# Required by example server.
#
chrono = { version = "0.4", features = ["serde"] }
futures = "0.1"
hyper = {version = "0.10", optional = true}
hyper-openssl = {version = "0.2", optional = true }
iron = {version = "0.5", optional = true}
swagger = "0.7"
hyper = {version = "0.11", optional = true}
hyper-tls = {version = "0.1.2", optional = true}
swagger = "0.9"
# Not required by example server.
#
bodyparser = {version = "0.7", optional = true}
url = "1.5"
lazy_static = "0.2"
log = "0.3.0"
multipart = {version = "0.13", optional = true}
router = {version = "0.5", optional = true}
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}
urlencoded = {version = "0.5", 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

View File

@@ -13,7 +13,7 @@ To see how to make this your own, look here:
[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md)
- API version: 1.0.0
- Build date: 2018-01-07T09:31:52.377-08:00
- Build date: 2018-02-06T14:00:33.084Z
This autogenerated project defines an API crate `petstore_api` which contains:
* An `Api` trait defining the API in Rust.

View File

@@ -70,8 +70,9 @@ paths:
operation_id: "add_pet"
uppercase_operation_id: "ADD_PET"
path: "/pet"
PATH_ID: "PET"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
noClientExample: true
put:
tags:
@@ -122,8 +123,9 @@ paths:
operation_id: "update_pet"
uppercase_operation_id: "UPDATE_PET"
path: "/pet"
PATH_ID: "PET"
hasPathParams: false
HttpMethod: "Put"
httpmethod: "put"
noClientExample: true
/pet/findByStatus:
get:
@@ -175,8 +177,9 @@ paths:
operation_id: "find_pets_by_status"
uppercase_operation_id: "FIND_PETS_BY_STATUS"
path: "/pet/findByStatus"
PATH_ID: "PET_FINDBYSTATUS"
hasPathParams: false
HttpMethod: "Get"
httpmethod: "get"
/pet/findByTags:
get:
tags:
@@ -224,8 +227,9 @@ paths:
operation_id: "find_pets_by_tags"
uppercase_operation_id: "FIND_PETS_BY_TAGS"
path: "/pet/findByTags"
PATH_ID: "PET_FINDBYTAGS"
hasPathParams: false
HttpMethod: "Get"
httpmethod: "get"
/pet/{petId}:
get:
tags:
@@ -270,8 +274,9 @@ paths:
operation_id: "get_pet_by_id"
uppercase_operation_id: "GET_PET_BY_ID"
path: "/pet/:petId"
PATH_ID: "PET_PETID"
hasPathParams: true
HttpMethod: "Get"
httpmethod: "get"
post:
tags:
- "pet"
@@ -319,8 +324,9 @@ paths:
operation_id: "update_pet_with_form"
uppercase_operation_id: "UPDATE_PET_WITH_FORM"
path: "/pet/:petId"
PATH_ID: "PET_PETID"
hasPathParams: true
HttpMethod: "Post"
httpmethod: "post"
delete:
tags:
- "pet"
@@ -358,8 +364,9 @@ paths:
operation_id: "delete_pet"
uppercase_operation_id: "DELETE_PET"
path: "/pet/:petId"
PATH_ID: "PET_PETID"
hasPathParams: true
HttpMethod: "Delete"
httpmethod: "delete"
/pet/{petId}/uploadImage:
post:
tags:
@@ -413,8 +420,9 @@ paths:
operation_id: "upload_file"
uppercase_operation_id: "UPLOAD_FILE"
path: "/pet/:petId/uploadImage"
PATH_ID: "PET_PETID_UPLOADIMAGE"
hasPathParams: true
HttpMethod: "Post"
httpmethod: "post"
hasFile: true
/store/inventory:
get:
@@ -444,8 +452,9 @@ paths:
operation_id: "get_inventory"
uppercase_operation_id: "GET_INVENTORY"
path: "/store/inventory"
PATH_ID: "STORE_INVENTORY"
hasPathParams: false
HttpMethod: "Get"
httpmethod: "get"
/store/order:
post:
tags:
@@ -488,8 +497,9 @@ paths:
operation_id: "place_order"
uppercase_operation_id: "PLACE_ORDER"
path: "/store/order"
PATH_ID: "STORE_ORDER"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
noClientExample: true
/store/order/{order_id}:
get:
@@ -536,8 +546,9 @@ paths:
operation_id: "get_order_by_id"
uppercase_operation_id: "GET_ORDER_BY_ID"
path: "/store/order/:order_id"
PATH_ID: "STORE_ORDER_ORDER_ID"
hasPathParams: true
HttpMethod: "Get"
httpmethod: "get"
delete:
tags:
- "store"
@@ -570,8 +581,9 @@ paths:
operation_id: "delete_order"
uppercase_operation_id: "DELETE_ORDER"
path: "/store/order/:order_id"
PATH_ID: "STORE_ORDER_ORDER_ID"
hasPathParams: true
HttpMethod: "Delete"
httpmethod: "delete"
/user:
post:
tags:
@@ -605,8 +617,9 @@ paths:
operation_id: "create_user"
uppercase_operation_id: "CREATE_USER"
path: "/user"
PATH_ID: "USER"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
noClientExample: true
/user/createWithArray:
post:
@@ -641,8 +654,9 @@ paths:
operation_id: "create_users_with_array_input"
uppercase_operation_id: "CREATE_USERS_WITH_ARRAY_INPUT"
path: "/user/createWithArray"
PATH_ID: "USER_CREATEWITHARRAY"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
/user/createWithList:
post:
tags:
@@ -676,8 +690,9 @@ paths:
operation_id: "create_users_with_list_input"
uppercase_operation_id: "CREATE_USERS_WITH_LIST_INPUT"
path: "/user/createWithList"
PATH_ID: "USER_CREATEWITHLIST"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
/user/login:
get:
tags:
@@ -716,7 +731,7 @@ paths:
X-Expires-After:
type: "string"
format: "date-time"
description: "date in UTC when toekn expires"
description: "date in UTC when token expires"
x-responseId: "SuccessfulOperation"
x-uppercaseResponseId: "SUCCESSFUL_OPERATION"
uppercase_operation_id: "LOGIN_USER"
@@ -730,8 +745,9 @@ paths:
operation_id: "login_user"
uppercase_operation_id: "LOGIN_USER"
path: "/user/login"
PATH_ID: "USER_LOGIN"
hasPathParams: false
HttpMethod: "Get"
httpmethod: "get"
/user/logout:
get:
tags:
@@ -752,8 +768,9 @@ paths:
operation_id: "logout_user"
uppercase_operation_id: "LOGOUT_USER"
path: "/user/logout"
PATH_ID: "USER_LOGOUT"
hasPathParams: false
HttpMethod: "Get"
httpmethod: "get"
/user/{username}:
get:
tags:
@@ -795,8 +812,9 @@ paths:
operation_id: "get_user_by_name"
uppercase_operation_id: "GET_USER_BY_NAME"
path: "/user/:username"
PATH_ID: "USER_USERNAME"
hasPathParams: true
HttpMethod: "Get"
httpmethod: "get"
put:
tags:
- "user"
@@ -841,8 +859,9 @@ paths:
operation_id: "update_user"
uppercase_operation_id: "UPDATE_USER"
path: "/user/:username"
PATH_ID: "USER_USERNAME"
hasPathParams: true
HttpMethod: "Put"
httpmethod: "put"
noClientExample: true
delete:
tags:
@@ -875,8 +894,9 @@ paths:
operation_id: "delete_user"
uppercase_operation_id: "DELETE_USER"
path: "/user/:username"
PATH_ID: "USER_USERNAME"
hasPathParams: true
HttpMethod: "Delete"
httpmethod: "delete"
/fake_classname_test:
patch:
tags:
@@ -916,8 +936,9 @@ paths:
operation_id: "test_classname"
uppercase_operation_id: "TEST_CLASSNAME"
path: "/fake_classname_test"
PATH_ID: "FAKE_CLASSNAME_TEST"
hasPathParams: false
HttpMethod: "Patch"
httpmethod: "patch"
noClientExample: true
/fake:
get:
@@ -1042,8 +1063,9 @@ paths:
operation_id: "test_enum_parameters"
uppercase_operation_id: "TEST_ENUM_PARAMETERS"
path: "/fake"
PATH_ID: "FAKE"
hasPathParams: false
HttpMethod: "Get"
httpmethod: "get"
post:
tags:
- "fake"
@@ -1195,8 +1217,9 @@ paths:
operation_id: "test_endpoint_parameters"
uppercase_operation_id: "TEST_ENDPOINT_PARAMETERS"
path: "/fake"
PATH_ID: "FAKE"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
patch:
tags:
- "fake"
@@ -1234,8 +1257,9 @@ paths:
operation_id: "test_client_model"
uppercase_operation_id: "TEST_CLIENT_MODEL"
path: "/fake"
PATH_ID: "FAKE"
hasPathParams: false
HttpMethod: "Patch"
httpmethod: "patch"
noClientExample: true
/fake/outer/number:
post:
@@ -1270,8 +1294,9 @@ paths:
operation_id: "fake_outer_number_serialize"
uppercase_operation_id: "FAKE_OUTER_NUMBER_SERIALIZE"
path: "/fake/outer/number"
PATH_ID: "FAKE_OUTER_NUMBER"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
/fake/outer/string:
post:
tags:
@@ -1305,8 +1330,9 @@ paths:
operation_id: "fake_outer_string_serialize"
uppercase_operation_id: "FAKE_OUTER_STRING_SERIALIZE"
path: "/fake/outer/string"
PATH_ID: "FAKE_OUTER_STRING"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
/fake/outer/boolean:
post:
tags:
@@ -1340,8 +1366,9 @@ paths:
operation_id: "fake_outer_boolean_serialize"
uppercase_operation_id: "FAKE_OUTER_BOOLEAN_SERIALIZE"
path: "/fake/outer/boolean"
PATH_ID: "FAKE_OUTER_BOOLEAN"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
/fake/outer/composite:
post:
tags:
@@ -1375,8 +1402,9 @@ paths:
operation_id: "fake_outer_composite_serialize"
uppercase_operation_id: "FAKE_OUTER_COMPOSITE_SERIALIZE"
path: "/fake/outer/composite"
PATH_ID: "FAKE_OUTER_COMPOSITE"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
/fake/jsonFormData:
get:
tags:
@@ -1410,8 +1438,9 @@ paths:
operation_id: "test_json_form_data"
uppercase_operation_id: "TEST_JSON_FORM_DATA"
path: "/fake/jsonFormData"
PATH_ID: "FAKE_JSONFORMDATA"
hasPathParams: false
HttpMethod: "Get"
httpmethod: "get"
/fake/inline-additionalProperties:
post:
tags:
@@ -1446,8 +1475,46 @@ paths:
operation_id: "test_inline_additional_properties"
uppercase_operation_id: "TEST_INLINE_ADDITIONAL_PROPERTIES"
path: "/fake/inline-additionalProperties"
PATH_ID: "FAKE_INLINE_ADDITIONALPROPERTIES"
hasPathParams: false
HttpMethod: "Post"
httpmethod: "post"
noClientExample: true
/fake/body-with-query-params:
put:
operationId: "testBodyWithQueryParams"
consumes:
- "application/json"
parameters:
- in: "body"
name: "body"
required: true
schema:
$ref: "#/definitions/User"
uppercase_data_type: "USER"
refName: "User"
formatString: "{:?}"
example: "???"
model_key: "OuterBoolean"
uppercase_operation_id: "TEST_BODY_WITH_QUERY_PARAMS"
consumesJson: true
- name: "query"
in: "query"
required: true
type: "string"
formatString: "\\\"{}\\\""
example: "\"query_example\".to_string()"
responses:
200:
description: "Success"
x-responseId: "Success"
x-uppercaseResponseId: "SUCCESS"
uppercase_operation_id: "TEST_BODY_WITH_QUERY_PARAMS"
operation_id: "test_body_with_query_params"
uppercase_operation_id: "TEST_BODY_WITH_QUERY_PARAMS"
path: "/fake/body-with-query-params"
PATH_ID: "FAKE_BODY_WITH_QUERY_PARAMS"
hasPathParams: false
HttpMethod: "Put"
noClientExample: true
/another-fake/dummy:
patch:
@@ -1487,8 +1554,9 @@ paths:
operation_id: "test_special_tags"
uppercase_operation_id: "TEST_SPECIAL_TAGS"
path: "/another-fake/dummy"
PATH_ID: "ANOTHER_FAKE_DUMMY"
hasPathParams: false
HttpMethod: "Patch"
httpmethod: "patch"
noClientExample: true
securityDefinitions:
petstore_auth:

View File

@@ -8,13 +8,16 @@ extern crate swagger;
#[allow(unused_extern_crates)]
extern crate uuid;
extern crate clap;
extern crate tokio_core;
#[allow(unused_imports)]
use futures::{Future, future, Stream, stream};
use tokio_core::reactor;
#[allow(unused_imports)]
use petstore_api::{ApiNoContext, ContextWrapperExt,
ApiError,
TestSpecialTagsResponse,
TestBodyWithQueryParamsResponse,
FakeOuterBooleanSerializeResponse,
FakeOuterCompositeSerializeResponse,
FakeOuterNumberSerializeResponse,
@@ -93,18 +96,19 @@ fn main() {
.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 is_https {
let client = if matches.is_present("https") {
// Using Simple HTTPS
petstore_api::Client::try_new_https(&base_url, "examples/ca.pem")
petstore_api::Client::try_new_https(core.handle(), &base_url, "examples/ca.pem")
.expect("Failed to create HTTPS client")
} else {
// Using HTTP
petstore_api::Client::try_new_http(&base_url)
petstore_api::Client::try_new_http(core.handle(), &base_url)
.expect("Failed to create HTTP client")
};
@@ -115,165 +119,171 @@ fn main() {
// Disabled because there's no example.
// Some("TestSpecialTags") => {
// let result = client.test_special_tags(???).wait();
// let result = core.run(client.test_special_tags(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },
// Disabled because there's no example.
// Some("TestBodyWithQueryParams") => {
// let result = core.run(client.test_body_with_query_params(???, "query_example".to_string()));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },
Some("FakeOuterBooleanSerialize") => {
let result = client.fake_outer_boolean_serialize(None).wait();
let result = core.run(client.fake_outer_boolean_serialize(None));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("FakeOuterCompositeSerialize") => {
let result = client.fake_outer_composite_serialize(None).wait();
let result = core.run(client.fake_outer_composite_serialize(None));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("FakeOuterNumberSerialize") => {
let result = client.fake_outer_number_serialize(None).wait();
let result = core.run(client.fake_outer_number_serialize(None));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("FakeOuterStringSerialize") => {
let result = client.fake_outer_string_serialize(None).wait();
let result = core.run(client.fake_outer_string_serialize(None));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
// Disabled because there's no example.
// Some("TestClientModel") => {
// let result = client.test_client_model(???).wait();
// let result = core.run(client.test_client_model(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },
Some("TestEndpointParameters") => {
let result = client.test_endpoint_parameters(8.14, 1.2, "pattern_without_delimiter_example".to_string(), swagger::ByteArray(Vec::from("B")), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Some(swagger::ByteArray(Vec::from("B"))), None, None, Some("password_example".to_string()), Some("callback_example".to_string())).wait();
let result = core.run(client.test_endpoint_parameters(8.14, 1.2, "pattern_without_delimiter_example".to_string(), swagger::ByteArray(Vec::from("B")), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Some(swagger::ByteArray(Vec::from("B"))), None, None, Some("password_example".to_string()), Some("callback_example".to_string())));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("TestEnumParameters") => {
let result = client.test_enum_parameters(Some(&Vec::new()), Some("enum_form_string_example".to_string()), Some(&Vec::new()), Some("enum_header_string_example".to_string()), Some(&Vec::new()), Some("enum_query_string_example".to_string()), Some(56), Some(1.2)).wait();
let result = core.run(client.test_enum_parameters(Some(&Vec::new()), Some("enum_form_string_example".to_string()), Some(&Vec::new()), Some("enum_header_string_example".to_string()), Some(&Vec::new()), Some("enum_query_string_example".to_string()), Some(56), Some(1.2)));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
// Disabled because there's no example.
// Some("TestInlineAdditionalProperties") => {
// let result = client.test_inline_additional_properties(???).wait();
// let result = core.run(client.test_inline_additional_properties(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },
Some("TestJsonFormData") => {
let result = client.test_json_form_data("param_example".to_string(), "param2_example".to_string()).wait();
let result = core.run(client.test_json_form_data("param_example".to_string(), "param2_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
// Disabled because there's no example.
// Some("TestClassname") => {
// let result = client.test_classname(???).wait();
// let result = core.run(client.test_classname(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },
// Disabled because there's no example.
// Some("AddPet") => {
// let result = client.add_pet(???).wait();
// let result = core.run(client.add_pet(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },
Some("DeletePet") => {
let result = client.delete_pet(789, Some("api_key_example".to_string())).wait();
let result = core.run(client.delete_pet(789, Some("api_key_example".to_string())));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("FindPetsByStatus") => {
let result = client.find_pets_by_status(&Vec::new()).wait();
let result = core.run(client.find_pets_by_status(&Vec::new()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("FindPetsByTags") => {
let result = client.find_pets_by_tags(&Vec::new()).wait();
let result = core.run(client.find_pets_by_tags(&Vec::new()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("GetPetById") => {
let result = client.get_pet_by_id(789).wait();
let result = core.run(client.get_pet_by_id(789));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
// Disabled because there's no example.
// Some("UpdatePet") => {
// let result = client.update_pet(???).wait();
// let result = core.run(client.update_pet(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },
Some("UpdatePetWithForm") => {
let result = client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string())).wait();
let result = core.run(client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string())));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("UploadFile") => {
let result = client.upload_file(789, Some("additional_metadata_example".to_string()), Box::new(future::ok(Some(Box::new(stream::once(Ok(b"hello".to_vec()))) as Box<Stream<Item=_, Error=_> + Send>))) as Box<Future<Item=_, Error=_> + Send>).wait();
let result = core.run(client.upload_file(789, Some("additional_metadata_example".to_string()), Box::new(future::ok(Some(Box::new(stream::once(Ok(b"hello".to_vec()))) as Box<Stream<Item=_, Error=_> + Send>))) as Box<Future<Item=_, Error=_> + Send>));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("DeleteOrder") => {
let result = client.delete_order("order_id_example".to_string()).wait();
let result = core.run(client.delete_order("order_id_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("GetInventory") => {
let result = client.get_inventory().wait();
let result = core.run(client.get_inventory());
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("GetOrderById") => {
let result = client.get_order_by_id(789).wait();
let result = core.run(client.get_order_by_id(789));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
// Disabled because there's no example.
// Some("PlaceOrder") => {
// let result = client.place_order(???).wait();
// let result = core.run(client.place_order(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },
// Disabled because there's no example.
// Some("CreateUser") => {
// let result = client.create_user(???).wait();
// let result = core.run(client.create_user(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },
Some("CreateUsersWithArrayInput") => {
let result = client.create_users_with_array_input(&Vec::new()).wait();
let result = core.run(client.create_users_with_array_input(&Vec::new()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("CreateUsersWithListInput") => {
let result = client.create_users_with_list_input(&Vec::new()).wait();
let result = core.run(client.create_users_with_list_input(&Vec::new()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("DeleteUser") => {
let result = client.delete_user("username_example".to_string()).wait();
let result = core.run(client.delete_user("username_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("GetUserByName") => {
let result = client.get_user_by_name("username_example".to_string()).wait();
let result = core.run(client.get_user_by_name("username_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("LoginUser") => {
let result = client.login_user("username_example".to_string(), "password_example".to_string()).wait();
let result = core.run(client.login_user("username_example".to_string(), "password_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
Some("LogoutUser") => {
let result = client.logout_user().wait();
let result = core.run(client.logout_user());
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
},
// Disabled because there's no example.
// Some("UpdateUser") => {
// let result = client.update_user("username_example".to_string(), ???).wait();
// let result = core.run(client.update_user("username_example".to_string(), ???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// },

View File

@@ -6,8 +6,11 @@
// extern crate <name of this crate>;
extern crate petstore_api;
extern crate swagger;
extern crate iron;
extern crate hyper_openssl;
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.
@@ -18,18 +21,19 @@ extern crate chrono;
#[macro_use]
extern crate error_chain;
use hyper_openssl::OpensslServer;
use hyper_openssl::openssl::x509::X509_FILETYPE_PEM;
use hyper_openssl::openssl::ssl::{SslAcceptorBuilder, SslMethod};
use hyper_openssl::openssl::error::ErrorStack;
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 iron::{Iron, Chain};
use swagger::auth::AllowAllMiddleware;
use swagger::auth::AllowAllAuthenticator;
mod server_lib;
/// Builds an SSL implementation for Simple HTTPS from some hard-coded file names
fn ssl() -> Result<OpensslServer, ErrorStack> {
// Builds an SSL implementation for Simple HTTPS from some hard-coded file names
fn ssl() -> Result<SslAcceptorBuilder, ErrorStack> {
let mut ssl = SslAcceptorBuilder::mozilla_intermediate_raw(SslMethod::tls())?;
// Server authentication
@@ -37,7 +41,7 @@ fn ssl() -> Result<OpensslServer, ErrorStack> {
ssl.set_certificate_chain_file("examples/server-chain.pem")?;
ssl.check_private_key()?;
Ok(OpensslServer::from(ssl.build()))
Ok(ssl)
}
/// Create custom server, wire it to the autogenerated router,
@@ -49,20 +53,22 @@ fn main() {
.help("Whether to use HTTPS or not"))
.get_matches();
let server = server_lib::server().unwrap();
let router = petstore_api::router(server);
let mut chain = Chain::new(router);
chain.link_before(petstore_api::server::ExtractAuthData);
// add authentication middlewares into the chain here
// for the purpose of this example, pretend we have authenticated a user
chain.link_before(AllowAllMiddleware::new("cosmo"));
let service_fn =
petstore_api::server::auth::NewService::new(
AllowAllAuthenticator::new(
server_lib::NewService,
"cosmo"
)
);
let addr = "127.0.0.1:80".parse().expect("Failed to parse bind address");
if matches.is_present("https") {
// Using Simple HTTPS
Iron::new(chain).https("localhost:80", ssl().expect("Failed to load SSL keys")).expect("Failed to start HTTPS server");
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
Iron::new(chain).http("localhost:80").expect("Failed to start HTTP server");
TcpServer::new(Http::new(), addr).serve(service_fn);
}
}

View File

@@ -7,8 +7,20 @@ mod errors {
}
pub use self::errors::*;
use std::io;
use hyper;
use petstore_api;
/// Instantiate a new server.
pub fn server() -> Result<server::Server> {
Ok(server::Server {})
pub struct NewService;
impl hyper::server::NewService for NewService {
type Request = (hyper::Request, petstore_api::Context);
type Response = hyper::Response;
type Error = hyper::Error;
type Instance = petstore_api::server::Service<server::Server>;
/// Instantiate a new server.
fn new_service(&self) -> io::Result<Self::Instance> {
Ok(petstore_api::server::Service::new(server::Server))
}
}

View File

@@ -7,10 +7,12 @@ use chrono;
use futures::Stream;
use std::collections::HashMap;
use std::io::Error;
use swagger;
use petstore_api::{Api, ApiError, Context,
TestSpecialTagsResponse,
TestBodyWithQueryParamsResponse,
FakeOuterBooleanSerializeResponse,
FakeOuterCompositeSerializeResponse,
FakeOuterNumberSerializeResponse,
@@ -50,133 +52,140 @@ pub struct Server;
impl Api for Server {
/// To test special tags
fn test_special_tags(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError> + Send> {
fn test_special_tags(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>> {
let context = context.clone();
println!("test_special_tags({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>, context: &Context) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError> + Send> {
fn test_body_with_query_params(&self, body: models::User, query: String, context: &Context) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>> {
let context = context.clone();
println!("test_body_with_query_params({:?}, \"{}\") - X-Span-ID: {:?}", body, query, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>, context: &Context) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>> {
let context = context.clone();
println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>, context: &Context) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError> + Send> {
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>, context: &Context) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>> {
let context = context.clone();
println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>, context: &Context) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError> + Send> {
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>, context: &Context) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>> {
let context = context.clone();
println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>, context: &Context) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError> + Send> {
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>, context: &Context) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>> {
let context = context.clone();
println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// To test \"client\" model
fn test_client_model(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClientModelResponse, Error=ApiError> + Send> {
fn test_client_model(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>> {
let context = context.clone();
println!("test_client_model({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>, context: &Context) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError> + Send> {
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>, context: &Context) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>> {
let context = context.clone();
println!("test_endpoint_parameters({}, {}, \"{}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// To test enum parameters
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>, context: &Context) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError> + Send> {
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>, context: &Context) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>> {
let context = context.clone();
println!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// test inline additionalProperties
fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError> + Send> {
fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>> {
let context = context.clone();
println!("test_inline_additional_properties({:?}) - X-Span-ID: {:?}", param, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// test json serialization of form data
fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError> + Send> {
fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>> {
let context = context.clone();
println!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// To test class name in snake case
fn test_classname(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClassnameResponse, Error=ApiError> + Send> {
fn test_classname(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>> {
let context = context.clone();
println!("test_classname({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Add a new pet to the store
fn add_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=AddPetResponse, Error=ApiError> + Send> {
fn add_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=AddPetResponse, Error=ApiError>> {
let context = context.clone();
println!("add_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Deletes a pet
fn delete_pet(&self, pet_id: i64, api_key: Option<String>, context: &Context) -> Box<Future<Item=DeletePetResponse, Error=ApiError> + Send> {
fn delete_pet(&self, pet_id: i64, api_key: Option<String>, context: &Context) -> Box<Future<Item=DeletePetResponse, Error=ApiError>> {
let context = context.clone();
println!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Finds Pets by status
fn find_pets_by_status(&self, status: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError> + Send> {
fn find_pets_by_status(&self, status: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError>> {
let context = context.clone();
println!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Finds Pets by tags
fn find_pets_by_tags(&self, tags: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError> + Send> {
fn find_pets_by_tags(&self, tags: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError>> {
let context = context.clone();
println!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Find pet by ID
fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError> + Send> {
fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>> {
let context = context.clone();
println!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Update an existing pet
fn update_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=UpdatePetResponse, Error=ApiError> + Send> {
fn update_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>> {
let context = context.clone();
println!("update_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Updates a pet in the store with form data
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>, context: &Context) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError> + Send> {
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>, context: &Context) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>> {
let context = context.clone();
println!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// uploads an image
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box<Future<Item=UploadFileResponse, Error=ApiError> + Send> {
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box<Future<Item=UploadFileResponse, Error=ApiError>> {
let context = context.clone();
println!("upload_file({}, {:?}, ) - X-Span-ID: {:?}", pet_id, additional_metadata, context.x_span_id.unwrap_or(String::from("<none>")).clone());
let _ = file; //Suppresses unused param warning
@@ -184,84 +193,84 @@ impl Api for Server {
}
/// Delete purchase order by ID
fn delete_order(&self, order_id: String, context: &Context) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError> + Send> {
fn delete_order(&self, order_id: String, context: &Context) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError>> {
let context = context.clone();
println!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Returns pet inventories by status
fn get_inventory(&self, context: &Context) -> Box<Future<Item=GetInventoryResponse, Error=ApiError> + Send> {
fn get_inventory(&self, context: &Context) -> Box<Future<Item=GetInventoryResponse, Error=ApiError>> {
let context = context.clone();
println!("get_inventory() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Find purchase order by ID
fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError> + Send> {
fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>> {
let context = context.clone();
println!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Place an order for a pet
fn place_order(&self, body: models::Order, context: &Context) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError> + Send> {
fn place_order(&self, body: models::Order, context: &Context) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>> {
let context = context.clone();
println!("place_order({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Create user
fn create_user(&self, body: models::User, context: &Context) -> Box<Future<Item=CreateUserResponse, Error=ApiError> + Send> {
fn create_user(&self, body: models::User, context: &Context) -> Box<Future<Item=CreateUserResponse, Error=ApiError>> {
let context = context.clone();
println!("create_user({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Creates list of users with given input array
fn create_users_with_array_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError> + Send> {
fn create_users_with_array_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>> {
let context = context.clone();
println!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Creates list of users with given input array
fn create_users_with_list_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError> + Send> {
fn create_users_with_list_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>> {
let context = context.clone();
println!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Delete user
fn delete_user(&self, username: String, context: &Context) -> Box<Future<Item=DeleteUserResponse, Error=ApiError> + Send> {
fn delete_user(&self, username: String, context: &Context) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>> {
let context = context.clone();
println!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Get user by user name
fn get_user_by_name(&self, username: String, context: &Context) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError> + Send> {
fn get_user_by_name(&self, username: String, context: &Context) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError>> {
let context = context.clone();
println!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Logs user into the system
fn login_user(&self, username: String, password: String, context: &Context) -> Box<Future<Item=LoginUserResponse, Error=ApiError> + Send> {
fn login_user(&self, username: String, password: String, context: &Context) -> Box<Future<Item=LoginUserResponse, Error=ApiError>> {
let context = context.clone();
println!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Logs out current logged in user session
fn logout_user(&self, context: &Context) -> Box<Future<Item=LogoutUserResponse, Error=ApiError> + Send> {
fn logout_user(&self, context: &Context) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>> {
let context = context.clone();
println!("logout_user() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Updated user
fn update_user(&self, username: String, body: models::User, context: &Context) -> Box<Future<Item=UpdateUserResponse, Error=ApiError> + Send> {
fn update_user(&self, username: String, body: models::User, context: &Context) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>> {
let context = context.clone();
println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, body, context.x_span_id.unwrap_or(String::from("<none>")).clone());
Box::new(futures::failed("Generic failure".into()))

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -3,10 +3,10 @@ extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serde_xml_rs;
extern crate futures;
extern crate chrono;
extern crate multipart;
#[macro_use]
extern crate lazy_static;
#[macro_use]
@@ -32,6 +32,8 @@ mod mimetypes;
pub use swagger::{ApiError, Context, ContextWrapper};
pub const BASE_PATH: &'static str = "/v2";
#[derive(Debug, PartialEq)]
pub enum TestSpecialTagsResponse {
@@ -39,6 +41,12 @@ pub enum TestSpecialTagsResponse {
SuccessfulOperation ( models::Client ) ,
}
#[derive(Debug, PartialEq)]
pub enum TestBodyWithQueryParamsResponse {
/// Success
Success ,
}
#[derive(Debug, PartialEq)]
pub enum FakeOuterBooleanSerializeResponse {
/// Output boolean
@@ -258,97 +266,100 @@ pub enum UpdateUserResponse {
pub trait Api {
/// To test special tags
fn test_special_tags(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError> + Send>;
fn test_special_tags(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>>;
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>, context: &Context) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError> + Send>;
fn test_body_with_query_params(&self, body: models::User, query: String, context: &Context) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>>;
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>, context: &Context) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError> + Send>;
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>, context: &Context) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>>;
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>, context: &Context) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError> + Send>;
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>, context: &Context) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>>;
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>, context: &Context) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError> + Send>;
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>, context: &Context) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>>;
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>, context: &Context) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>>;
/// To test \"client\" model
fn test_client_model(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClientModelResponse, Error=ApiError> + Send>;
fn test_client_model(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>>;
/// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>, context: &Context) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError> + Send>;
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>, context: &Context) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>>;
/// To test enum parameters
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>, context: &Context) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError> + Send>;
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>, context: &Context) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>>;
/// test inline additionalProperties
fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError> + Send>;
fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>>;
/// test json serialization of form data
fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError> + Send>;
fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>>;
/// To test class name in snake case
fn test_classname(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClassnameResponse, Error=ApiError> + Send>;
fn test_classname(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>>;
/// Add a new pet to the store
fn add_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=AddPetResponse, Error=ApiError> + Send>;
fn add_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=AddPetResponse, Error=ApiError>>;
/// Deletes a pet
fn delete_pet(&self, pet_id: i64, api_key: Option<String>, context: &Context) -> Box<Future<Item=DeletePetResponse, Error=ApiError> + Send>;
fn delete_pet(&self, pet_id: i64, api_key: Option<String>, context: &Context) -> Box<Future<Item=DeletePetResponse, Error=ApiError>>;
/// Finds Pets by status
fn find_pets_by_status(&self, status: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError> + Send>;
fn find_pets_by_status(&self, status: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError>>;
/// Finds Pets by tags
fn find_pets_by_tags(&self, tags: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError> + Send>;
fn find_pets_by_tags(&self, tags: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError>>;
/// Find pet by ID
fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError> + Send>;
fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>>;
/// Update an existing pet
fn update_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=UpdatePetResponse, Error=ApiError> + Send>;
fn update_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>>;
/// Updates a pet in the store with form data
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>, context: &Context) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError> + Send>;
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>, context: &Context) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>>;
/// uploads an image
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box<Future<Item=UploadFileResponse, Error=ApiError> + Send>;
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box<Future<Item=UploadFileResponse, Error=ApiError>>;
/// Delete purchase order by ID
fn delete_order(&self, order_id: String, context: &Context) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError> + Send>;
fn delete_order(&self, order_id: String, context: &Context) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError>>;
/// Returns pet inventories by status
fn get_inventory(&self, context: &Context) -> Box<Future<Item=GetInventoryResponse, Error=ApiError> + Send>;
fn get_inventory(&self, context: &Context) -> Box<Future<Item=GetInventoryResponse, Error=ApiError>>;
/// Find purchase order by ID
fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError> + Send>;
fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>>;
/// Place an order for a pet
fn place_order(&self, body: models::Order, context: &Context) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError> + Send>;
fn place_order(&self, body: models::Order, context: &Context) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>>;
/// Create user
fn create_user(&self, body: models::User, context: &Context) -> Box<Future<Item=CreateUserResponse, Error=ApiError> + Send>;
fn create_user(&self, body: models::User, context: &Context) -> Box<Future<Item=CreateUserResponse, Error=ApiError>>;
/// Creates list of users with given input array
fn create_users_with_array_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError> + Send>;
fn create_users_with_array_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>>;
/// Creates list of users with given input array
fn create_users_with_list_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError> + Send>;
fn create_users_with_list_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>>;
/// Delete user
fn delete_user(&self, username: String, context: &Context) -> Box<Future<Item=DeleteUserResponse, Error=ApiError> + Send>;
fn delete_user(&self, username: String, context: &Context) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>>;
/// Get user by user name
fn get_user_by_name(&self, username: String, context: &Context) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError> + Send>;
fn get_user_by_name(&self, username: String, context: &Context) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError>>;
/// Logs user into the system
fn login_user(&self, username: String, password: String, context: &Context) -> Box<Future<Item=LoginUserResponse, Error=ApiError> + Send>;
fn login_user(&self, username: String, password: String, context: &Context) -> Box<Future<Item=LoginUserResponse, Error=ApiError>>;
/// Logs out current logged in user session
fn logout_user(&self, context: &Context) -> Box<Future<Item=LogoutUserResponse, Error=ApiError> + Send>;
fn logout_user(&self, context: &Context) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>>;
/// Updated user
fn update_user(&self, username: String, body: models::User, context: &Context) -> Box<Future<Item=UpdateUserResponse, Error=ApiError> + Send>;
fn update_user(&self, username: String, body: models::User, context: &Context) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>>;
}
@@ -356,97 +367,100 @@ pub trait Api {
pub trait ApiNoContext {
/// To test special tags
fn test_special_tags(&self, body: models::Client) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError> + Send>;
fn test_special_tags(&self, body: models::Client) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>>;
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError> + Send>;
fn test_body_with_query_params(&self, body: models::User, query: String) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>>;
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError> + Send>;
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>>;
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError> + Send>;
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>>;
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError> + Send>;
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>>;
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>>;
/// To test \"client\" model
fn test_client_model(&self, body: models::Client) -> Box<Future<Item=TestClientModelResponse, Error=ApiError> + Send>;
fn test_client_model(&self, body: models::Client) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>>;
/// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError> + Send>;
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>>;
/// To test enum parameters
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError> + Send>;
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>>;
/// test inline additionalProperties
fn test_inline_additional_properties(&self, param: object) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError> + Send>;
fn test_inline_additional_properties(&self, param: object) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>>;
/// test json serialization of form data
fn test_json_form_data(&self, param: String, param2: String) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError> + Send>;
fn test_json_form_data(&self, param: String, param2: String) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>>;
/// To test class name in snake case
fn test_classname(&self, body: models::Client) -> Box<Future<Item=TestClassnameResponse, Error=ApiError> + Send>;
fn test_classname(&self, body: models::Client) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>>;
/// Add a new pet to the store
fn add_pet(&self, body: models::Pet) -> Box<Future<Item=AddPetResponse, Error=ApiError> + Send>;
fn add_pet(&self, body: models::Pet) -> Box<Future<Item=AddPetResponse, Error=ApiError>>;
/// Deletes a pet
fn delete_pet(&self, pet_id: i64, api_key: Option<String>) -> Box<Future<Item=DeletePetResponse, Error=ApiError> + Send>;
fn delete_pet(&self, pet_id: i64, api_key: Option<String>) -> Box<Future<Item=DeletePetResponse, Error=ApiError>>;
/// Finds Pets by status
fn find_pets_by_status(&self, status: &Vec<String>) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError> + Send>;
fn find_pets_by_status(&self, status: &Vec<String>) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError>>;
/// Finds Pets by tags
fn find_pets_by_tags(&self, tags: &Vec<String>) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError> + Send>;
fn find_pets_by_tags(&self, tags: &Vec<String>) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError>>;
/// Find pet by ID
fn get_pet_by_id(&self, pet_id: i64) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError> + Send>;
fn get_pet_by_id(&self, pet_id: i64) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>>;
/// Update an existing pet
fn update_pet(&self, body: models::Pet) -> Box<Future<Item=UpdatePetResponse, Error=ApiError> + Send>;
fn update_pet(&self, body: models::Pet) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>>;
/// Updates a pet in the store with form data
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError> + Send>;
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>>;
/// uploads an image
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>) -> Box<Future<Item=UploadFileResponse, Error=ApiError> + Send>;
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>) -> Box<Future<Item=UploadFileResponse, Error=ApiError>>;
/// Delete purchase order by ID
fn delete_order(&self, order_id: String) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError> + Send>;
fn delete_order(&self, order_id: String) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError>>;
/// Returns pet inventories by status
fn get_inventory(&self) -> Box<Future<Item=GetInventoryResponse, Error=ApiError> + Send>;
fn get_inventory(&self) -> Box<Future<Item=GetInventoryResponse, Error=ApiError>>;
/// Find purchase order by ID
fn get_order_by_id(&self, order_id: i64) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError> + Send>;
fn get_order_by_id(&self, order_id: i64) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>>;
/// Place an order for a pet
fn place_order(&self, body: models::Order) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError> + Send>;
fn place_order(&self, body: models::Order) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>>;
/// Create user
fn create_user(&self, body: models::User) -> Box<Future<Item=CreateUserResponse, Error=ApiError> + Send>;
fn create_user(&self, body: models::User) -> Box<Future<Item=CreateUserResponse, Error=ApiError>>;
/// Creates list of users with given input array
fn create_users_with_array_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError> + Send>;
fn create_users_with_array_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>>;
/// Creates list of users with given input array
fn create_users_with_list_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError> + Send>;
fn create_users_with_list_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>>;
/// Delete user
fn delete_user(&self, username: String) -> Box<Future<Item=DeleteUserResponse, Error=ApiError> + Send>;
fn delete_user(&self, username: String) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>>;
/// Get user by user name
fn get_user_by_name(&self, username: String) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError> + Send>;
fn get_user_by_name(&self, username: String) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError>>;
/// Logs user into the system
fn login_user(&self, username: String, password: String) -> Box<Future<Item=LoginUserResponse, Error=ApiError> + Send>;
fn login_user(&self, username: String, password: String) -> Box<Future<Item=LoginUserResponse, Error=ApiError>>;
/// Logs out current logged in user session
fn logout_user(&self) -> Box<Future<Item=LogoutUserResponse, Error=ApiError> + Send>;
fn logout_user(&self) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>>;
/// Updated user
fn update_user(&self, username: String, body: models::User) -> Box<Future<Item=UpdateUserResponse, Error=ApiError> + Send>;
fn update_user(&self, username: String, body: models::User) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>>;
}
@@ -465,157 +479,162 @@ impl<'a, T: Api + Sized> ContextWrapperExt<'a> for T {
impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> {
/// To test special tags
fn test_special_tags(&self, body: models::Client) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError> + Send> {
fn test_special_tags(&self, body: models::Client) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>> {
self.api().test_special_tags(body, &self.context())
}
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError> + Send> {
fn test_body_with_query_params(&self, body: models::User, query: String) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>> {
self.api().test_body_with_query_params(body, query, &self.context())
}
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>> {
self.api().fake_outer_boolean_serialize(body, &self.context())
}
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError> + Send> {
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>> {
self.api().fake_outer_composite_serialize(body, &self.context())
}
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError> + Send> {
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>> {
self.api().fake_outer_number_serialize(body, &self.context())
}
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError> + Send> {
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>> {
self.api().fake_outer_string_serialize(body, &self.context())
}
/// To test \"client\" model
fn test_client_model(&self, body: models::Client) -> Box<Future<Item=TestClientModelResponse, Error=ApiError> + Send> {
fn test_client_model(&self, body: models::Client) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>> {
self.api().test_client_model(body, &self.context())
}
/// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError> + Send> {
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>> {
self.api().test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, &self.context())
}
/// To test enum parameters
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError> + Send> {
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>> {
self.api().test_enum_parameters(enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, &self.context())
}
/// test inline additionalProperties
fn test_inline_additional_properties(&self, param: object) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError> + Send> {
fn test_inline_additional_properties(&self, param: object) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>> {
self.api().test_inline_additional_properties(param, &self.context())
}
/// test json serialization of form data
fn test_json_form_data(&self, param: String, param2: String) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError> + Send> {
fn test_json_form_data(&self, param: String, param2: String) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>> {
self.api().test_json_form_data(param, param2, &self.context())
}
/// To test class name in snake case
fn test_classname(&self, body: models::Client) -> Box<Future<Item=TestClassnameResponse, Error=ApiError> + Send> {
fn test_classname(&self, body: models::Client) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>> {
self.api().test_classname(body, &self.context())
}
/// Add a new pet to the store
fn add_pet(&self, body: models::Pet) -> Box<Future<Item=AddPetResponse, Error=ApiError> + Send> {
fn add_pet(&self, body: models::Pet) -> Box<Future<Item=AddPetResponse, Error=ApiError>> {
self.api().add_pet(body, &self.context())
}
/// Deletes a pet
fn delete_pet(&self, pet_id: i64, api_key: Option<String>) -> Box<Future<Item=DeletePetResponse, Error=ApiError> + Send> {
fn delete_pet(&self, pet_id: i64, api_key: Option<String>) -> Box<Future<Item=DeletePetResponse, Error=ApiError>> {
self.api().delete_pet(pet_id, api_key, &self.context())
}
/// Finds Pets by status
fn find_pets_by_status(&self, status: &Vec<String>) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError> + Send> {
fn find_pets_by_status(&self, status: &Vec<String>) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError>> {
self.api().find_pets_by_status(status, &self.context())
}
/// Finds Pets by tags
fn find_pets_by_tags(&self, tags: &Vec<String>) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError> + Send> {
fn find_pets_by_tags(&self, tags: &Vec<String>) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError>> {
self.api().find_pets_by_tags(tags, &self.context())
}
/// Find pet by ID
fn get_pet_by_id(&self, pet_id: i64) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError> + Send> {
fn get_pet_by_id(&self, pet_id: i64) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>> {
self.api().get_pet_by_id(pet_id, &self.context())
}
/// Update an existing pet
fn update_pet(&self, body: models::Pet) -> Box<Future<Item=UpdatePetResponse, Error=ApiError> + Send> {
fn update_pet(&self, body: models::Pet) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>> {
self.api().update_pet(body, &self.context())
}
/// Updates a pet in the store with form data
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError> + Send> {
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>> {
self.api().update_pet_with_form(pet_id, name, status, &self.context())
}
/// uploads an image
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>) -> Box<Future<Item=UploadFileResponse, Error=ApiError> + Send> {
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>) -> Box<Future<Item=UploadFileResponse, Error=ApiError>> {
self.api().upload_file(pet_id, additional_metadata, file, &self.context())
}
/// Delete purchase order by ID
fn delete_order(&self, order_id: String) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError> + Send> {
fn delete_order(&self, order_id: String) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError>> {
self.api().delete_order(order_id, &self.context())
}
/// Returns pet inventories by status
fn get_inventory(&self) -> Box<Future<Item=GetInventoryResponse, Error=ApiError> + Send> {
fn get_inventory(&self) -> Box<Future<Item=GetInventoryResponse, Error=ApiError>> {
self.api().get_inventory(&self.context())
}
/// Find purchase order by ID
fn get_order_by_id(&self, order_id: i64) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError> + Send> {
fn get_order_by_id(&self, order_id: i64) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>> {
self.api().get_order_by_id(order_id, &self.context())
}
/// Place an order for a pet
fn place_order(&self, body: models::Order) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError> + Send> {
fn place_order(&self, body: models::Order) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>> {
self.api().place_order(body, &self.context())
}
/// Create user
fn create_user(&self, body: models::User) -> Box<Future<Item=CreateUserResponse, Error=ApiError> + Send> {
fn create_user(&self, body: models::User) -> Box<Future<Item=CreateUserResponse, Error=ApiError>> {
self.api().create_user(body, &self.context())
}
/// Creates list of users with given input array
fn create_users_with_array_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError> + Send> {
fn create_users_with_array_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>> {
self.api().create_users_with_array_input(body, &self.context())
}
/// Creates list of users with given input array
fn create_users_with_list_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError> + Send> {
fn create_users_with_list_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>> {
self.api().create_users_with_list_input(body, &self.context())
}
/// Delete user
fn delete_user(&self, username: String) -> Box<Future<Item=DeleteUserResponse, Error=ApiError> + Send> {
fn delete_user(&self, username: String) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>> {
self.api().delete_user(username, &self.context())
}
/// Get user by user name
fn get_user_by_name(&self, username: String) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError> + Send> {
fn get_user_by_name(&self, username: String) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError>> {
self.api().get_user_by_name(username, &self.context())
}
/// Logs user into the system
fn login_user(&self, username: String, password: String) -> Box<Future<Item=LoginUserResponse, Error=ApiError> + Send> {
fn login_user(&self, username: String, password: String) -> Box<Future<Item=LoginUserResponse, Error=ApiError>> {
self.api().login_user(username, password, &self.context())
}
/// Logs out current logged in user session
fn logout_user(&self) -> Box<Future<Item=LogoutUserResponse, Error=ApiError> + Send> {
fn logout_user(&self) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>> {
self.api().logout_user(&self.context())
}
/// Updated user
fn update_user(&self, username: String, body: models::User) -> Box<Future<Item=UpdateUserResponse, Error=ApiError> + Send> {
fn update_user(&self, username: String, body: models::User) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>> {
self.api().update_user(username, body, &self.context())
}
@@ -633,6 +652,6 @@ pub mod server;
// Re-export router() as a top-level name
#[cfg(feature = "server")]
pub use self::server::router;
pub use self::server::Service;
pub mod models;

View File

@@ -61,30 +61,46 @@ pub mod requests {
lazy_static! {
pub static ref TEST_SPECIAL_TAGS: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for TestBodyWithQueryParams
lazy_static! {
pub static ref TEST_BODY_WITH_QUERY_PARAMS: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for FakeOuterBooleanSerialize
lazy_static! {
pub static ref FAKE_OUTER_BOOLEAN_SERIALIZE: Mime = "Application/Json".parse().unwrap();
pub static ref FAKE_OUTER_BOOLEAN_SERIALIZE: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for FakeOuterCompositeSerialize
lazy_static! {
pub static ref FAKE_OUTER_COMPOSITE_SERIALIZE: Mime = "Application/Json".parse().unwrap();
pub static ref FAKE_OUTER_COMPOSITE_SERIALIZE: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for FakeOuterNumberSerialize
lazy_static! {
pub static ref FAKE_OUTER_NUMBER_SERIALIZE: Mime = "Application/Json".parse().unwrap();
pub static ref FAKE_OUTER_NUMBER_SERIALIZE: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for FakeOuterStringSerialize
lazy_static! {
pub static ref FAKE_OUTER_STRING_SERIALIZE: Mime = "Application/Json".parse().unwrap();
pub static ref FAKE_OUTER_STRING_SERIALIZE: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for TestClientModel
lazy_static! {
pub static ref TEST_CLIENT_MODEL: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for TestEndpointParameters
lazy_static! {
pub static ref TEST_ENDPOINT_PARAMETERS: Mime = "application/xml; charset=utf-8".parse().unwrap();
}
/// Create Mime objects for the request content types for TestEnumParameters
lazy_static! {
pub static ref TEST_ENUM_PARAMETERS: Mime = "*/*".parse().unwrap();
}
/// Create Mime objects for the request content types for TestInlineAdditionalProperties
lazy_static! {
pub static ref TEST_INLINE_ADDITIONAL_PROPERTIES: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for TestJsonFormData
lazy_static! {
pub static ref TEST_JSON_FORM_DATA: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for TestClassname
lazy_static! {
pub static ref TEST_CLASSNAME: Mime = "application/json".parse().unwrap();
@@ -97,25 +113,29 @@ pub mod requests {
lazy_static! {
pub static ref UPDATE_PET: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for UpdatePetWithForm
lazy_static! {
pub static ref UPDATE_PET_WITH_FORM: Mime = "application/x-www-form-urlencoded".parse().unwrap();
}
/// Create Mime objects for the request content types for PlaceOrder
lazy_static! {
pub static ref PLACE_ORDER: Mime = "Application/Json".parse().unwrap();
pub static ref PLACE_ORDER: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for CreateUser
lazy_static! {
pub static ref CREATE_USER: Mime = "Application/Json".parse().unwrap();
pub static ref CREATE_USER: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for CreateUsersWithArrayInput
lazy_static! {
pub static ref CREATE_USERS_WITH_ARRAY_INPUT: Mime = "Application/Json".parse().unwrap();
pub static ref CREATE_USERS_WITH_ARRAY_INPUT: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for CreateUsersWithListInput
lazy_static! {
pub static ref CREATE_USERS_WITH_LIST_INPUT: Mime = "Application/Json".parse().unwrap();
pub static ref CREATE_USERS_WITH_LIST_INPUT: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for UpdateUser
lazy_static! {
pub static ref UPDATE_USER: Mime = "Application/Json".parse().unwrap();
pub static ref UPDATE_USER: Mime = "application/json".parse().unwrap();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
use std::io;
use hyper;
use hyper::{Request, Response, Error, StatusCode};
use server::url::form_urlencoded;
use swagger::auth::{Authorization, AuthData, Scopes};
use Api;
pub struct NewService<T> where T: hyper::server::NewService<Request=(Request,Option<AuthData>), Response=Response, Error=Error> {
inner: T,
}
impl<T> NewService<T> where T: hyper::server::NewService<Request=(Request,Option<AuthData>), Response=Response, Error=Error> + 'static {
pub fn new(inner: T) -> NewService<T> {
NewService{inner}
}
}
impl<T> hyper::server::NewService for NewService<T> where T: hyper::server::NewService<Request=(Request,Option<AuthData>), Response=Response, Error=Error> + 'static {
type Request = Request;
type Response = Response;
type Error = Error;
type Instance = Service<T::Instance>;
fn new_service(&self) -> Result<Self::Instance, io::Error> {
self.inner.new_service().map(|s| Service::new(s))
}
}
/// Middleware to extract authentication data from request
pub struct Service<T> where T: hyper::server::Service<Request=(Request,Option<AuthData>), Response=Response, Error=Error> {
inner: T,
}
impl<T> Service<T> where T: hyper::server::Service<Request=(Request,Option<AuthData>), Response=Response, Error=Error> {
pub fn new(inner: T) -> Service<T> {
Service{inner}
}
}
impl<T> hyper::server::Service for Service<T> where T: hyper::server::Service<Request=(Request,Option<AuthData>), Response=Response, Error=Error> {
type Request = Request;
type Response = Response;
type Error = Error;
type Future = T::Future;
fn call(&self, req: Self::Request) -> Self::Future {
{
header! { (ApiKey1, "api_key") => [String] }
if let Some(header) = req.headers().get::<ApiKey1>().cloned() {
let auth_data = AuthData::ApiKey(header.0);
return self.inner.call((req, Some(auth_data)));
}
}
{
let key = form_urlencoded::parse(req.query().unwrap_or_default().as_bytes())
.filter(|e| e.0 == "api_key_query")
.map(|e| e.1.clone().into_owned())
.nth(0);
if let Some(key) = key {
let auth_data = AuthData::ApiKey(key);
return self.inner.call((req, Some(auth_data)));
}
}
{
use hyper::header::{Authorization, Basic, Bearer};
use std::ops::Deref;
if let Some(basic) = req.headers().get::<Authorization<Basic>>().cloned() {
let auth_data = AuthData::Basic(basic.deref().clone());
return self.inner.call((req, Some(auth_data)));
}
}
{
use hyper::header::{Authorization, Basic, Bearer};
use std::ops::Deref;
if let Some(bearer) = req.headers().get::<Authorization<Bearer>>().cloned() {
let auth_data = AuthData::Bearer(bearer.deref().clone());
return self.inner.call((req, Some(auth_data)));
}
}
return self.inner.call((req, None));
}
}

File diff suppressed because it is too large Load Diff