#![allow(unused_extern_crates)]
extern crate tokio_core;
extern crate native_tls;
extern crate hyper_tls;
extern crate openssl;
extern crate mime;
extern crate chrono;
extern crate url;
use hyper;
use hyper::header::{Headers, ContentType};
use hyper::Uri;
use self::url::percent_encoding::{utf8_percent_encode, PATH_SEGMENT_ENCODE_SET, QUERY_ENCODE_SET};
use futures;
use futures::{Future, Stream};
use futures::{future, stream};
use self::tokio_core::reactor::Handle;
use std::borrow::Cow;
use std::io::{Read, Error, ErrorKind};
use std::error;
use std::fmt;
use std::path::Path;
use std::sync::Arc;
use std::str;
use std::str::FromStr;
use std::string::ToString;
use mimetypes;
use serde_json;
#[allow(unused_imports)]
use std::collections::{HashMap, BTreeMap};
#[allow(unused_imports)]
use swagger;
use swagger::{ApiError, XSpanId, XSpanIdString, Has, AuthData};
use {Api,
ApiResponse,
GetResponse,
HatResponse,
HatOffResponse,
HatOnResponse,
ScanResponse
};
use models;
define_encode_set! {
pub ID_ENCODE_SET = [PATH_SEGMENT_ENCODE_SET] | {'|'}
}
fn into_base_path(input: &str, correct_scheme: Option<&'static str>) -> Result<String, ClientInitError> {
let uri = Uri::from_str(input)?;
let scheme = uri.scheme().ok_or(ClientInitError::InvalidScheme)?;
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))
}
pub struct Client<F> where
F: Future<Item=hyper::Response, Error=hyper::Error> + 'static {
client_service: Arc<Box<hyper::client::Service<Request=hyper::Request<hyper::Body>, Response=hyper::Response, Error=hyper::Error, Future=F>>>,
base_path: String,
}
impl<F> fmt::Debug for Client<F> where
F: Future<Item=hyper::Response, Error=hyper::Error> + 'static {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Client {{ base_path: {} }}", self.base_path)
}
}
impl<F> Clone for Client<F> where
F: Future<Item=hyper::Response, Error=hyper::Error> + 'static {
fn clone(&self) -> Self {
Client {
client_service: self.client_service.clone(),
base_path: self.base_path.clone()
}
}
}
impl Client<hyper::client::FutureResponse> {
pub fn try_new_http(handle: Handle, base_path: &str) -> Result<Client<hyper::client::FutureResponse>, ClientInitError> {
let http_connector = swagger::http_connector();
Self::try_new_with_connector::<hyper::client::HttpConnector>(
handle,
base_path,
Some("http"),
http_connector,
)
}
pub fn try_new_https<CA>(
handle: Handle,
base_path: &str,
ca_certificate: CA,
) -> Result<Client<hyper::client::FutureResponse>, 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,
)
}
pub fn try_new_https_mutual<CA, K, C>(
handle: Handle,
base_path: &str,
ca_certificate: CA,
client_key: K,
client_certificate: C,
) -> Result<Client<hyper::client::FutureResponse>, 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,
)
}
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<hyper::client::FutureResponse>, ClientInitError>
where
C: hyper::client::Connect + hyper::client::Service,
{
let connector = connector_fn(&handle);
let client_service = Box::new(hyper::Client::configure().connector(connector).build(
&handle,
));
Ok(Client {
client_service: Arc::new(client_service),
base_path: into_base_path(base_path, protocol)?,
})
}
#[deprecated(note="Use try_new_with_client_service instead")]
pub fn try_new_with_hyper_client(
hyper_client: Arc<Box<hyper::client::Service<Request=hyper::Request<hyper::Body>, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>>>,
handle: Handle,
base_path: &str
) -> Result<Client<hyper::client::FutureResponse>, ClientInitError>
{
Ok(Client {
client_service: hyper_client,
base_path: into_base_path(base_path, None)?,
})
}
}
impl<F> Client<F> where
F: Future<Item=hyper::Response, Error=hyper::Error> + 'static
{
pub fn try_new_with_client_service(client_service: Arc<Box<hyper::client::Service<Request=hyper::Request<hyper::Body>, Response=hyper::Response, Error=hyper::Error, Future=F>>>,
handle: Handle,
base_path: &str)
-> Result<Client<F>, ClientInitError>
{
Ok(Client {
client_service: client_service,
base_path: into_base_path(base_path, None)?,
})
}
}
impl<F, C> Api<C> for Client<F> where
F: Future<Item=hyper::Response, Error=hyper::Error> + 'static,
C: Has<XSpanIdString> {
fn api(&self, context: &C) -> Box<Future<Item=ApiResponse, Error=ApiError>> {
let mut uri = format!(
"{}/mbus/api",
self.base_path
);
let uri = match Uri::from_str(&uri) {
Ok(uri) => uri,
Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))),
};
let mut request = hyper::Request::new(hyper::Method::Get, uri);
request.headers_mut().set(XSpanId((context as &Has<XSpanIdString>).get().0.clone()));
Box::new(self.client_service.call(request)
.map_err(|e| ApiError(format!("No response received: {}", e)))
.and_then(|mut response| {
match response.status().as_u16() {
200 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
ApiResponse::OK(body)
)
) as Box<Future<Item=_, Error=_>>
},
404 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
ApiResponse::NotFound(body)
)
) as Box<Future<Item=_, Error=_>>
},
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=_>>
}
}
}))
}
fn get(&self, param_device: String, param_baudrate: models::Baudrate, param_address: i32, context: &C) -> Box<Future<Item=GetResponse, Error=ApiError>> {
let mut uri = format!(
"{}/mbus/get/{device}/{baudrate}/{address}",
self.base_path, device=utf8_percent_encode(¶m_device.to_string(), ID_ENCODE_SET), baudrate=utf8_percent_encode(¶m_baudrate.to_string(), ID_ENCODE_SET), address=utf8_percent_encode(¶m_address.to_string(), ID_ENCODE_SET)
);
let uri = match Uri::from_str(&uri) {
Ok(uri) => uri,
Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))),
};
let mut request = hyper::Request::new(hyper::Method::Post, uri);
request.headers_mut().set(XSpanId((context as &Has<XSpanIdString>).get().0.clone()));
Box::new(self.client_service.call(request)
.map_err(|e| ApiError(format!("No response received: {}", e)))
.and_then(|mut response| {
match response.status().as_u16() {
200 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
GetResponse::OK(body)
)
) as Box<Future<Item=_, Error=_>>
},
400 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
GetResponse::BadRequest(body)
)
) as Box<Future<Item=_, Error=_>>
},
404 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
GetResponse::NotFound(body)
)
) as Box<Future<Item=_, Error=_>>
},
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=_>>
}
}
}))
}
fn hat(&self, context: &C) -> Box<Future<Item=HatResponse, Error=ApiError>> {
let mut uri = format!(
"{}/mbus/hat",
self.base_path
);
let uri = match Uri::from_str(&uri) {
Ok(uri) => uri,
Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))),
};
let mut request = hyper::Request::new(hyper::Method::Get, uri);
request.headers_mut().set(XSpanId((context as &Has<XSpanIdString>).get().0.clone()));
Box::new(self.client_service.call(request)
.map_err(|e| ApiError(format!("No response received: {}", e)))
.and_then(|mut response| {
match response.status().as_u16() {
200 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
serde_json::from_str::<models::Hat>(body)
.map_err(|e| e.into())
))
.map(move |body|
HatResponse::OK(body)
)
) as Box<Future<Item=_, Error=_>>
},
404 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
HatResponse::NotFound(body)
)
) as Box<Future<Item=_, Error=_>>
},
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=_>>
}
}
}))
}
fn hat_off(&self, context: &C) -> Box<Future<Item=HatOffResponse, Error=ApiError>> {
let mut uri = format!(
"{}/mbus/hat/off",
self.base_path
);
let uri = match Uri::from_str(&uri) {
Ok(uri) => uri,
Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))),
};
let mut request = hyper::Request::new(hyper::Method::Post, uri);
request.headers_mut().set(XSpanId((context as &Has<XSpanIdString>).get().0.clone()));
Box::new(self.client_service.call(request)
.map_err(|e| ApiError(format!("No response received: {}", e)))
.and_then(|mut response| {
match response.status().as_u16() {
200 => {
let body = response.body();
Box::new(
future::ok(
HatOffResponse::OK
)
) as Box<Future<Item=_, Error=_>>
},
404 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
HatOffResponse::NotFound(body)
)
) as Box<Future<Item=_, Error=_>>
},
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=_>>
}
}
}))
}
fn hat_on(&self, context: &C) -> Box<Future<Item=HatOnResponse, Error=ApiError>> {
let mut uri = format!(
"{}/mbus/hat/on",
self.base_path
);
let uri = match Uri::from_str(&uri) {
Ok(uri) => uri,
Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))),
};
let mut request = hyper::Request::new(hyper::Method::Post, uri);
request.headers_mut().set(XSpanId((context as &Has<XSpanIdString>).get().0.clone()));
Box::new(self.client_service.call(request)
.map_err(|e| ApiError(format!("No response received: {}", e)))
.and_then(|mut response| {
match response.status().as_u16() {
200 => {
let body = response.body();
Box::new(
future::ok(
HatOnResponse::OK
)
) as Box<Future<Item=_, Error=_>>
},
404 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
HatOnResponse::NotFound(body)
)
) as Box<Future<Item=_, Error=_>>
},
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=_>>
}
}
}))
}
fn scan(&self, param_device: String, param_baudrate: models::Baudrate, context: &C) -> Box<Future<Item=ScanResponse, Error=ApiError>> {
let mut uri = format!(
"{}/mbus/scan/{device}/{baudrate}",
self.base_path, device=utf8_percent_encode(¶m_device.to_string(), ID_ENCODE_SET), baudrate=utf8_percent_encode(¶m_baudrate.to_string(), ID_ENCODE_SET)
);
let uri = match Uri::from_str(&uri) {
Ok(uri) => uri,
Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))),
};
let mut request = hyper::Request::new(hyper::Method::Post, uri);
request.headers_mut().set(XSpanId((context as &Has<XSpanIdString>).get().0.clone()));
Box::new(self.client_service.call(request)
.map_err(|e| ApiError(format!("No response received: {}", e)))
.and_then(|mut response| {
match response.status().as_u16() {
200 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
ScanResponse::OK(body)
)
) as Box<Future<Item=_, Error=_>>
},
400 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
ScanResponse::BadRequest(body)
)
) as Box<Future<Item=_, Error=_>>
},
404 => {
let body = response.body();
Box::new(
body
.concat2()
.map_err(|e| ApiError(format!("Failed to read response: {}", e)))
.and_then(|body| str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))
.and_then(|body|
Ok(body.to_string())
))
.map(move |body|
ScanResponse::NotFound(body)
)
) as Box<Future<Item=_, Error=_>>
},
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=_>>
}
}
}))
}
}
#[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."
}
}